diff --git a/CMakeLists.txt b/CMakeLists.txt index e20b6ede..ba3ddc0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,7 +67,7 @@ find_package(protobuf REQUIRED) find_package(gRPC REQUIRED) ############################################################ -# PROTO , 遇到proto 的生成问题,现在build 目录执行 cmake --install . --verbose ,然后编译即可 +# PROTO ############################################################ set(PROTO_IMPORT_DIR ${PROJECT_SOURCE_DIR}/protos) @@ -76,9 +76,10 @@ file(MAKE_DIRECTORY ${PROTO_BINARY_DIR}) file(GLOB_RECURSE PROTO_FILES ${PROTO_IMPORT_DIR}/*.proto) -set(Protobuf_PROTOC_EXECUTABLE "${CMAKE_INSTALL_PREFIX}/bin/protoc" CACHE FILEPATH "" FORCE) -set_property(TARGET gRPC::grpc_cpp_plugin - PROPERTY IMPORTED_LOCATION "${CMAKE_INSTALL_PREFIX}/bin/grpc_cpp_plugin" +# Run bundled tools with their libraries, without requiring output/bin first. +set(PROTOC_COMMAND_OPTIONS -E env + "LD_LIBRARY_PATH=$" + "$" ) # 1) 先做 OBJECT:只负责生成/编译 pb.cc @@ -88,12 +89,16 @@ set_target_properties(proto-objects PROPERTIES POSITION_INDEPENDENT_CODE ON) protobuf_generate( TARGET proto-objects + PROTOC_EXE "${CMAKE_COMMAND}" + PROTOC_OPTIONS ${PROTOC_COMMAND_OPTIONS} IMPORT_DIRS ${PROTO_IMPORT_DIR} PROTOC_OUT_DIR ${PROTO_BINARY_DIR} USAGE_REQUIREMENT PRIVATE ) protobuf_generate( TARGET proto-objects + PROTOC_EXE "${CMAKE_COMMAND}" + PROTOC_OPTIONS ${PROTOC_COMMAND_OPTIONS} LANGUAGE grpc GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc PLUGIN "protoc-gen-grpc=$" diff --git a/README.md b/README.md index 1bcb8565..f03e1c5b 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,15 @@ CMVR-ES 工程。 +机械臂已提供独立的 OMPL RRTConnect 关节路径规划模块。`MotorRobotArm::moveP` 已接入路径规划、 +五次 B 样条平滑、运动限值校验与碰撞复检,并按控制周期下发电机指令。 + +运行时自碰撞监测位于 `cmvr-es/safety/self_collision`:`SelfCollisionMonitor` +通过 `RobotArm` 接口读取反馈、触发保护停止并协调恢复,碰撞计算仍由 +`algorithms/collision_detection` 中的 `CollisionChecker` 完成。 +`SelfCollisionTask` 仅绑定机械臂和转发周期调度;Monitor 不创建线程,恢复调用期间 +须继续周期检测。现有 `self_collision_task` 配置格式保持不变。 + ## 安装 ### 1. 拉取 Git 子模块 @@ -58,6 +67,9 @@ sudo apt install gnuplot-qt dependency/x86/third_party/ethercat/v1.7.0 ``` +当前依赖的源码提交和配套内核版本记录在该目录的 `BUILDINFO.txt` 中。 +目录中保留的其他内核版本模块不代表与当前 userspace 兼容。 + 先设置本机路径: ```shell @@ -72,7 +84,8 @@ sudo apt-get update sudo apt-get install -y linux-headers-$(uname -r) ``` -如果内置目录里已经有当前内核版本的 EtherCAT 内核模块,直接安装到系统: +只有在内置 userspace(`libethercat.so`、`ecrt.h`)与 EtherCAT 内核模块来自 +同一个源码提交,并且模块对应当前内核版本时,才可以直接安装到系统: ```shell sudo mkdir -p /lib/modules/$(uname -r)/ethercat @@ -80,7 +93,11 @@ sudo cp -r $IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)/ethercat/* /lib/modules/$( sudo depmod ``` -内置内核模块只适用于相同内核版本。如果 `$IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)` 不存在,说明这台机器的内核版本不匹配,需要在这台机器上重新编译安装 IgH EtherCAT: +不能只根据 `uname -r` 和 IgH `1.7.0` 版本号判断兼容性。同一个稳定分支的不同 +提交也可能使用不同的 ioctl 数据结构,混用后会出现 +`Failed to create slave config: Inappropriate ioctl for device`。如果无法确认 userspace +和内核模块来自同一提交,或者 `$IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)` 不存在, +需要在这台机器上使用同一份源码重新编译安装 IgH EtherCAT: ```shell sudo apt-get update @@ -91,6 +108,7 @@ sudo apt-get install -y \ cd /tmp git clone --branch stable-1.7 --depth 1 https://gitlab.com/etherlab.org/ethercat.git ethercat-stable-1.7 cd ethercat-stable-1.7 +git rev-parse HEAD # 记录本次 userspace 和内核模块共同使用的提交 ./bootstrap ./configure \ @@ -108,10 +126,30 @@ sudo make modules_install sudo depmod ``` +其中,`make install` 会更新 `$IGH_ETHERCAT_ROOT` 下的用户态库、头文件和工具, +也会覆盖该目录中的默认配置文件;已有网卡配置应先备份并在安装后恢复。 +`sudo make modules_install` 会更新 `/lib/modules/$(uname -r)/ethercat` 下的 +`ec_master.ko`、`ec_generic.ko` 等内核模块。已加载的模块需要通过下方启动脚本 +停止并重新加载后才会使用新文件;执行前应退出正在占用主站的应用。 + +安装完成后,检查用户态库与内核模块中的“创建 slave config” ioctl 编号。 +使用 `libethercat.so.1` 符号链接,避免把实际库文件名固定为旧的 `1.2.0`: + +```shell +objdump -d --disassemble=ecrt_master_slave_config "$IGH_ETHERCAT_ROOT/lib/libethercat.so.1" \ + | rg -o -m1 '\$0x[cC][0-9a-fA-F]+a423' + +objdump -d "/lib/modules/$(uname -r)/ethercat/master/ec_master.ko" \ + | rg -o -m1 '\$0x[cC][0-9a-fA-F]+a423' +``` + +两条命令的输出必须完全一致。编号不同说明 ABI 不兼容,不能启动 EtherCAT 应用; +编号一致是必要检查,仍需保证用户态和内核模块来自同一源码提交。 + 启动 EtherCAT。`eno1` 换成实际连接 EtherCAT 从站的网卡: ```shell -sudo script/ethercat/start_ethercat.sh eno1 +sudo scripts/ethercat/start_ethercat.sh eno1 ``` 脚本会写入内置 IgH 配置文件: @@ -125,7 +163,7 @@ $IGH_ETHERCAT_ROOT/etc/ethercat.conf 查看状态: ```shell -script/ethercat/status_ethercat.sh +scripts/ethercat/status_ethercat.sh $IGH_ETHERCAT_ROOT/bin/ethercat master $IGH_ETHERCAT_ROOT/bin/ethercat slaves @@ -135,6 +173,33 @@ $IGH_ETHERCAT_ROOT/bin/ethercat pdos 停止 EtherCAT: ```shell -sudo script/ethercat/stop_ethercat.sh eno1 -sudo script/ethercat/stop_ethercat.sh eno1 --restore-network +sudo scripts/ethercat/stop_ethercat.sh eno1 +sudo scripts/ethercat/stop_ethercat.sh eno1 --restore-network ``` + +### 4. 编译并安装 + +项目脚本统一位于 `scripts/`,用途见 [脚本索引](scripts/README.md)。 + +在项目根目录执行,不传参数默认使用 `Debug`,也可显式选择构建类型: + +```shell +./scripts/build.sh +./scripts/build.sh Debug +./scripts/build.sh Release +./scripts/build.sh RelWithDebInfo +``` + +三种类型分别使用 `build/Debug`、`build/Release`、`build/RelWithDebInfo`, +重复执行会增量编译。编译成功后自动安装到 `output`;编译失败不会执行安装。 +日常运行和性能测试建议使用 `RelWithDebInfo`,保留调试信息并开启优化。 +预编译的第三方库直接复用,不会随构建类型重新编译。 + +默认使用 4 个编译任务,可通过环境变量调整: + +```shell +CMAKE_BUILD_PARALLEL_LEVEL=2 ./scripts/build.sh RelWithDebInfo +``` + +安装会更新 `output/bin`、`output/lib`,并用源码目录的配置和模型替换 +`output/bin/config`、`output/bin/model`;需要保留的配置应修改在源码目录中。 diff --git a/cmvr-es/CMakeLists.txt b/cmvr-es/CMakeLists.txt index 0ff7c443..85b3f209 100644 --- a/cmvr-es/CMakeLists.txt +++ b/cmvr-es/CMakeLists.txt @@ -3,6 +3,8 @@ link_libraries(cmvr_es::logging) add_subdirectory(common) add_subdirectory(hardware) +add_subdirectory(curves) +add_subdirectory(environment) add_subdirectory(algorithms) add_subdirectory(simulate) add_subdirectory(devices) diff --git a/cmvr-es/algorithms/CMakeLists.txt b/cmvr-es/algorithms/CMakeLists.txt index 471f0dfe..0e7333a7 100644 --- a/cmvr-es/algorithms/CMakeLists.txt +++ b/cmvr-es/algorithms/CMakeLists.txt @@ -1,4 +1,6 @@ add_subdirectory(motion_planner) +add_subdirectory(planner) +add_subdirectory(smoother) add_subdirectory(kinematics/ik_solver) add_subdirectory(perception) add_subdirectory(controllers) diff --git a/cmvr-es/algorithms/collision_detection/CMakeLists.txt b/cmvr-es/algorithms/collision_detection/CMakeLists.txt index f6401175..8c28d9ba 100644 --- a/cmvr-es/algorithms/collision_detection/CMakeLists.txt +++ b/cmvr-es/algorithms/collision_detection/CMakeLists.txt @@ -46,3 +46,49 @@ target_compile_definitions(self_collision_benchmark PRIVATE ) install(TARGETS self_collision_checker LIBRARY DESTINATION lib) + +add_library(collision_checker SHARED + src/collision_checker.cpp + src/distance_sampling_policy.cpp +) + +target_include_directories(collision_checker PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} +) + +target_compile_definitions(collision_checker PRIVATE + COAL_DISABLE_HPP_FCL_WARNINGS +) + +target_link_libraries(collision_checker PUBLIC + cmvr_es::environment + cmvr_es::proto +) +target_link_libraries(collision_checker PRIVATE coal) + +add_library(cmvr_es::collision_checker ALIAS collision_checker) + +add_executable(collision_checker_test + test/collision_checker_test.cpp +) +target_link_libraries(collision_checker_test PRIVATE + cmvr_es::collision_checker + gtest + gtest_main + pthread +) +target_compile_definitions(collision_checker_test PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" +) + +add_executable(lgv_collision_benchmark + benchmark/collision_benchmark.cpp +) +target_link_libraries(lgv_collision_benchmark PRIVATE + cmvr_es::collision_checker +) +target_compile_definitions(lgv_collision_benchmark PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" +) + +install(TARGETS collision_checker LIBRARY DESTINATION lib) diff --git a/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp new file mode 100644 index 00000000..17c1b8e8 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +#include "algorithms/collision_detection/include/collision_checker.h" + +int main() +{ + const std::string urdf_path = std::string(CMVR_ES_SOURCE_DIR) + + "/model/xiaoyan_description/dual_arm_collision.urdf"; + const std::vector joint_names{ + "R_SHOULDER_P", "R_SHOULDER_R", "R_SHOULDER_Y", "R_ELBOW_R", + "R_WRIST_P", "R_WRIST_Y", "R_WRIST_R", + }; + + cmvr::CollisionChecker checker; + std::string error; + if (!checker.init(urdf_path, joint_names, {}, &error)) { + std::cerr << "Initialization failed: " << error << '\n'; + return 1; + } + + constexpr std::size_t kIterations = 2000; + std::vector samples_us; + samples_us.reserve(kIterations); + std::vector q(joint_names.size(), 0.0); + for (std::size_t iteration = 0; iteration < kIterations; ++iteration) { + q[0] = 0.2 * static_cast(iteration % 100) / 100.0; + const auto begin = std::chrono::steady_clock::now(); + const auto result = checker.check(q); + const auto end = std::chrono::steady_clock::now(); + if (!result.valid) { + std::cerr << "Collision check failed: " << result.error << '\n'; + return 1; + } + samples_us.push_back(std::chrono::duration(end - begin).count()); + } + + std::sort(samples_us.begin(), samples_us.end()); + double total_us = 0.0; + for (const double sample : samples_us) { + total_us += sample; + } + const std::size_t p99_index = static_cast(0.99 * (samples_us.size() - 1)); + std::cout << "active_pairs=" << checker.activePairCount() << '\n' + << "iterations=" << samples_us.size() << '\n' + << "average_us=" << total_us / samples_us.size() << '\n' + << "p99_us=" << samples_us[p99_index] << '\n' + << "max_us=" << samples_us.back() << '\n'; + return 0; +} diff --git a/cmvr-es/algorithms/collision_detection/include/collision_checker.h b/cmvr-es/algorithms/collision_detection/include/collision_checker.h new file mode 100644 index 00000000..5d48e8c8 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/include/collision_checker.h @@ -0,0 +1,131 @@ +#ifndef CMVR_ES_COLLISION_CHECKER_H +#define CMVR_ES_COLLISION_CHECKER_H + +#include +#include +#include +#include +#include + +#include + +#include "common/types/arm/arm_types.h" +#include "environment/include/robot_model.h" + +namespace cmvr { + +namespace config { +class CollisionCheckerConfig; +} + +struct CollisionPair { + std::string first; + std::string second; +}; + +struct BoxObstacle { + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + std::string name; + // Existing URDF frame fixed to the model root. Pose describes the box center. + std::string frame_id; + Eigen::Vector3d size_m{Eigen::Vector3d::Zero()}; + Eigen::Vector3d position_m{Eigen::Vector3d::Zero()}; + Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; +}; + +struct CollisionOptions { + std::vector ignored_pairs; + // Copied at init; robot-world pairs are never excluded by ignored_pairs. + std::vector obstacles; +}; + +struct CollisionResult { + bool valid{false}; + bool in_collision{false}; + double minimum_distance_m{0.0}; + std::string first; + std::string second; + std::string error; +}; + +struct CollisionValidationOptions { + double minimum_distance_m{0.0}; + // Maximum accumulated joint-space step between discrete collision checks. + double joint_step_rad{0.02}; + std::function&)> additional_state_valid; + std::function is_cancelled; +}; + +struct CollisionTrajectoryResult { + bool valid{false}; + std::size_t validity_checks{0}; + std::string error; +}; + +// Instances own distance-query caches; not thread-safe. +class CollisionChecker { +public: + CollisionChecker(); + ~CollisionChecker(); + + CollisionChecker(CollisionChecker&&) noexcept; + CollisionChecker& operator=(CollisionChecker&&) noexcept; + + CollisionChecker(const CollisionChecker&) = delete; + CollisionChecker& operator=(const CollisionChecker&) = delete; + + // RobotModel computes body poses; this checker owns pair rules and distance + // queries. A model without collision geometry fails initialization. + bool init(const RobotModel& model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error = nullptr); + + bool init(const std::string& urdf_path, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error = nullptr); + + // Resolves the configured URDF and self-collision pair rules. + // A failed init clears the previous checker state. + bool init(const config::CollisionCheckerConfig& config, + const std::vector& active_joint_names, + std::string* error = nullptr); + + // Reuses matching model geometry, or loads the configured collision URDF + // into a local model copy. The caller's model is never modified. + bool init(const config::CollisionCheckerConfig& config, + const RobotModel& model, + std::string* error = nullptr); + + // Returns the selected robot bodies at these joint positions; invalid input throws. + std::vector collisionBodies(const std::vector& joint_positions) const; + + CollisionResult check(const std::vector& bodies); + CollisionResult check(const std::vector& joint_positions); + + // Invalid queries throw; collisions and additional constraint failures + // return false. Additional constraints cannot bypass geometry checks. + bool isStateValid(const std::vector& joint_positions, + const CollisionValidationOptions& options = {}); + + // Checks the position polyline, including both endpoints. This is discrete + // checking; joint limits and motion derivative limits belong to the caller. + CollisionTrajectoryResult checkTrajectory( + const device::JointTrajectory& trajectory, + const CollisionValidationOptions& options = {}); + + bool initialized() const; + std::size_t dof() const; + std::size_t activePairCount() const; + const std::vector& jointNames() const; + +private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace cmvr + +#endif // CMVR_ES_COLLISION_CHECKER_H diff --git a/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h new file mode 100644 index 00000000..30399118 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h @@ -0,0 +1,47 @@ +#ifndef CMVR_ES_DISTANCE_SAMPLING_POLICY_H +#define CMVR_ES_DISTANCE_SAMPLING_POLICY_H + +#include +#include +#include + +#include "environment/include/robot_model.h" + +namespace cmvr { + +struct DistanceSamplingOptions { + double max_geometry_displacement_m{0.002}; + double max_check_period_s{0.01}; +}; + +class LgvDistanceSamplingPolicy { +public: + using Clock = std::chrono::steady_clock; + + bool configure(const DistanceSamplingOptions& options, + std::string* error = nullptr); + + bool shouldCheck(const std::vector& current, + Clock::time_point now) const; + + void markChecked(const std::vector& current, + Clock::time_point now); + + void reset(); + + double displacementSinceLastCheck( + const std::vector& current) const; + + bool hasBaseline() const { return has_baseline_; } + +private: + DistanceSamplingOptions options_{}; + std::vector last_checked_{}; + Clock::time_point last_check_time_{}; + bool configured_{false}; + bool has_baseline_{false}; +}; + +} // namespace cmvr + +#endif // CMVR_ES_DISTANCE_SAMPLING_POLICY_H diff --git a/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp b/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp new file mode 100644 index 00000000..973b910a --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp @@ -0,0 +1,468 @@ +#include "algorithms/collision_detection/include/collision_checker.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "cmvr/config/collision_config.pb.h" +#include "common/config/config_files.h" + +namespace cmvr { +namespace { + +using LinkPairKey = std::pair; + +LinkPairKey canonicalPair(std::string first, std::string second) +{ + if (second < first) { + std::swap(first, second); + } + return {std::move(first), std::move(second)}; +} + +void setError(std::string* error, const std::string& message) +{ + if (error) { + *error = message; + } +} + +} // namespace + +class CollisionChecker::Impl { +public: + bool init(const RobotModel& robot_model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) + { + reset(); + const auto reject = [&](const std::string& message) { + reset(); + setError(error, message); + return false; + }; + if (!robot_model.hasCollisionGeometry()) { + return reject("RobotModel contains no collision geometry"); + } + if (active_joint_names.empty()) { + return reject("Active joint list is empty"); + } + robot_model_ = robot_model; + joint_names_ = active_joint_names; + const auto bodies = robot_model_.collisionBodies( + std::vector(joint_names_.size(), 0.0), joint_names_); + if (bodies.empty()) { + return reject("No collision geometry remains after arm filtering"); + } + + std::unordered_set selected_link_names; + for (const auto& body : bodies) { + if (!body.geometry) { + return reject("Collision geometry is null for link: " + body.link_name); + } + geometry_indices_.push_back(body.geometry_index); + objects_.push_back({body.link_name, body.geometry, coal::Transform3s::Identity()}); + selected_link_names.insert(body.link_name); + } + std::set ignored_pairs; + for (const auto& pair : options.ignored_pairs) { + if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) { + return reject("Ignored collision pairs require two different non-empty links"); + } + if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) { + return reject("Ignored collision pair references an inactive or unknown link: " + + pair.first + ", " + pair.second); + } + ignored_pairs.insert(canonicalPair(pair.first, pair.second)); + } + for (std::size_t first = 0; first < bodies.size(); ++first) { + for (std::size_t second = first + 1; second < bodies.size(); ++second) { + const auto& a = bodies[first]; + const auto& b = bodies[second]; + if (a.joint_name == b.joint_name || a.parent_joint_name == b.joint_name || + b.parent_joint_name == a.joint_name || + ignored_pairs.count(canonicalPair(a.link_name, b.link_name))) { + continue; + } + pairs_.emplace_back(first, second, objects_); + } + } + + std::unordered_set obstacle_names; + for (const auto& obstacle : options.obstacles) { + if (obstacle.name.empty() || !obstacle_names.insert(obstacle.name).second || + robot_model_.containsName(obstacle.name)) { + return reject("Obstacle name must be unique and distinct from robot names: " + + obstacle.name); + } + Eigen::Isometry3d frame_pose; + if (!robot_model_.fixedFramePose(obstacle.frame_id, frame_pose)) { + return reject("Cannot resolve fixed obstacle frame: " + obstacle.frame_id); + } + const double orientation_norm = obstacle.orientation.norm(); + if (!obstacle.size_m.allFinite() || (obstacle.size_m.array() <= 0.0).any() || + !obstacle.position_m.allFinite() || !obstacle.orientation.coeffs().allFinite() || + !std::isfinite(orientation_norm) || + orientation_norm <= std::numeric_limits::epsilon()) { + return reject("Obstacle requires positive finite sizes and a valid pose: " + + obstacle.name); + } + Eigen::Isometry3d box_pose = Eigen::Isometry3d::Identity(); + box_pose.linear() = obstacle.orientation.normalized().toRotationMatrix(); + box_pose.translation() = obstacle.position_m; + const Eigen::Isometry3d placement = frame_pose * box_pose; + if (!placement.matrix().allFinite()) { + return reject("Obstacle transform is not finite: " + obstacle.name); + } + auto box = std::make_shared( + obstacle.size_m.x(), obstacle.size_m.y(), obstacle.size_m.z()); + box->computeLocalAABB(); + const auto obstacle_index = objects_.size(); + objects_.push_back({obstacle.name, std::move(box), + coal::Transform3s(placement.linear(), placement.translation())}); + // World pairs include every selected robot body, including the base. + for (std::size_t robot_index = 0; robot_index < bodies.size(); ++robot_index) { + pairs_.emplace_back(robot_index, obstacle_index, objects_); + } + } + if (pairs_.empty()) { + return reject("No active collision pairs remain after filtering"); + } + initialized_ = true; + setError(error, ""); + return true; + } + + std::vector collisionBodies(const std::vector& joint_positions) const + { + if (!initialized_) { + throw std::logic_error("CollisionChecker is not initialized"); + } + return robot_model_.collisionBodies(joint_positions, joint_names_); + } + + CollisionResult check(const std::vector& bodies) + { + CollisionResult result; + if (!initialized_) { + result.error = "CollisionChecker is not initialized"; + return result; + } + if (bodies.size() != geometry_indices_.size()) { + result.error = "Collision body count does not match initialized geometry"; + return result; + } + for (std::size_t index = 0; index < bodies.size(); ++index) { + const auto& pose = bodies[index]; + if (pose.geometry_index != geometry_indices_[index]) { + result.error = "Collision body geometry order is invalid"; + return result; + } + const double norm = pose.orientation.norm(); + if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() || + !std::isfinite(norm) || norm <= std::numeric_limits::epsilon()) { + result.error = "Collision body contains an invalid pose"; + return result; + } + objects_[index].placement = coal::Transform3s( + pose.orientation.normalized().toRotationMatrix(), pose.position); + } + // World placements are fixed and independent of the supplied robot body poses. + try { + result.minimum_distance_m = std::numeric_limits::infinity(); + for (auto& pair : pairs_) { + pair.result.clear(); + pair.compute(objects_[pair.first].placement, objects_[pair.second].placement, + pair.request, pair.result); + const double distance = pair.result.min_distance; + if (!std::isfinite(distance)) { + result.error = "Collision distance is not finite"; + return result; + } + if (distance < result.minimum_distance_m) { + result.minimum_distance_m = distance; + result.first = objects_[pair.first].name; + result.second = objects_[pair.second].name; + } + } + result.in_collision = result.minimum_distance_m <= 0.0; + result.valid = true; + } catch (const std::exception& exception) { + result.error = "Collision distance computation failed: " + std::string(exception.what()); + } + return result; + } + + CollisionResult check(const std::vector& joint_positions) + { + try { + return check(collisionBodies(joint_positions)); + } catch (const std::exception& exception) { + CollisionResult result; + result.error = exception.what(); + return result; + } + } + + void reset() + { + initialized_ = false; + joint_names_.clear(); + pairs_.clear(); + objects_.clear(); + geometry_indices_.clear(); + robot_model_ = RobotModel{}; + } + + struct QueryObject { + std::string name; + std::shared_ptr geometry; + coal::Transform3s placement; + }; + + struct DistancePair { + std::size_t first; + std::size_t second; + coal::ComputeDistance compute; + coal::DistanceRequest request{true}; + coal::DistanceResult result; + + DistancePair(std::size_t a, std::size_t b, const std::vector& objects) + : first(a), second(b), compute(objects[a].geometry.get(), objects[b].geometry.get()) + { + request.enable_signed_distance = true; + request.enable_cached_gjk_guess = true; + } + }; + + bool initialized_{false}; + std::vector joint_names_; + RobotModel robot_model_; + std::vector geometry_indices_; + std::vector objects_; + std::vector pairs_; +}; + +CollisionChecker::CollisionChecker() + : impl_(std::make_unique()) +{ +} + +CollisionChecker::~CollisionChecker() = default; +CollisionChecker::CollisionChecker(CollisionChecker&&) noexcept = default; +CollisionChecker& CollisionChecker::operator=(CollisionChecker&&) noexcept = default; + +bool CollisionChecker::init(const RobotModel& model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) +{ + try { + return impl_->init(model, active_joint_names, options, error); + } catch (const std::exception& exception) { + impl_->reset(); + setError(error, "Failed to initialize collision checker: " + std::string(exception.what())); + return false; + } +} + +bool CollisionChecker::init(const std::string& urdf_path, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) +{ + impl_->reset(); + RobotModel model; + if (!model.loadUrdf(urdf_path) || !model.loadCollisionGeometry(urdf_path)) { + setError(error, "Failed to load robot collision model: " + urdf_path); + return false; + } + return init(model, active_joint_names, options, error); +} + +bool CollisionChecker::init(const config::CollisionCheckerConfig& config, + const std::vector& active_joint_names, + std::string* error) +{ + RobotModel model; + model.dof = active_joint_names.size(); + model.joint_names = active_joint_names; + return init(config, model, error); +} + +bool CollisionChecker::init(const config::CollisionCheckerConfig& config, + const RobotModel& robot_model, + std::string* error) +{ + impl_->reset(); + try { + CollisionOptions options; + for (const auto& pair : config.ignored_pairs()) { + options.ignored_pairs.push_back({pair.first(), pair.second()}); + } + auto model = robot_model; + if (!config.urdf_path().empty()) { + const auto path = ConfigHelper::resolveResourceFile(config.urdf_path()); + if (model.collisionUrdfPath().empty() || + std::filesystem::weakly_canonical(path) != + std::filesystem::weakly_canonical(model.collisionUrdfPath())) { + if ((!model.hasKinematics() && !model.loadUrdf(path)) || + !model.loadCollisionGeometry(path)) { + setError(error, "Failed to load robot collision model: " + path); + return false; + } + } + } + return init(model, robot_model.joint_names, options, error); + } catch (const std::exception& exception) { + impl_->reset(); + setError(error, "Failed to initialize collision checker: " + std::string(exception.what())); + return false; + } +} + +std::vector CollisionChecker::collisionBodies( + const std::vector& joint_positions) const +{ + return impl_->collisionBodies(joint_positions); +} + +CollisionResult CollisionChecker::check(const std::vector& bodies) +{ + return impl_->check(bodies); +} + +CollisionResult CollisionChecker::check(const std::vector& joint_positions) +{ + return impl_->check(joint_positions); +} + +bool CollisionChecker::isStateValid(const std::vector& joint_positions, + const CollisionValidationOptions& options) +{ + if (!std::isfinite(options.minimum_distance_m) || options.minimum_distance_m < 0.0) { + throw std::invalid_argument("Collision minimum distance must be finite and non-negative"); + } + const auto collision = check(joint_positions); + if (!collision.valid) { + throw std::runtime_error(collision.error); + } + if (collision.in_collision || !(collision.minimum_distance_m > options.minimum_distance_m)) { + return false; + } + return !options.additional_state_valid || options.additional_state_valid(joint_positions); +} + +CollisionTrajectoryResult CollisionChecker::checkTrajectory( + const device::JointTrajectory& trajectory, const CollisionValidationOptions& options) +{ + CollisionTrajectoryResult result; + if (!initialized()) { + result.error = "CollisionChecker is not initialized"; + return result; + } + if (trajectory.empty()) { + result.error = "Collision trajectory is empty"; + return result; + } + if (!std::isfinite(options.joint_step_rad) || options.joint_step_rad <= 0.0 || + !std::isfinite(options.minimum_distance_m) || options.minimum_distance_m < 0.0) { + result.error = "Collision validation requires a positive finite joint step and non-negative finite clearance"; + return result; + } + + try { + std::vector checked_position(dof()); + double distance_to_check = 0.0; + for (std::size_t i = 0; i < trajectory.size(); ++i) { + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + const auto& to = trajectory[i].position; + const auto& from = trajectory[i == 0 ? 0 : i - 1].position; + if (to.size() != dof()) { + result.error = "Collision trajectory joint position size mismatch at sample " + std::to_string(i); + return result; + } + double maximum_delta = 0.0; + for (std::size_t joint = 0; joint < dof(); ++joint) { + const double delta = to[joint] - from[joint]; + if (!std::isfinite(to[joint]) || !std::isfinite(delta)) { + result.error = "Collision trajectory has a non-finite position or segment at sample " + std::to_string(i); + return result; + } + maximum_delta = std::max(maximum_delta, std::abs(delta)); + } + // Sum each segment's maximum joint increment. Keeping the remainder + // across segments prevents reversals from cancelling travel distance. + while (distance_to_check <= maximum_delta || i + 1 == trajectory.size()) { + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + if (result.validity_checks >= 1000000) { + result.error = "Collision trajectory validation exceeds one million checks"; + return result; + } + const double ratio = maximum_delta > 0.0 + ? std::min(1.0, distance_to_check / maximum_delta) : 1.0; + for (std::size_t joint = 0; joint < dof(); ++joint) { + checked_position[joint] = ratio == 1.0 + ? to[joint] + : from[joint] + ratio * (to[joint] - from[joint]); + } + ++result.validity_checks; + if (!isStateValid(checked_position, options)) { + result.error = "Trajectory failed collision/clearance or additional constraint check at sample " + + std::to_string(i); + return result; + } + distance_to_check += options.joint_step_rad; + if (ratio == 1.0) break; + } + distance_to_check -= maximum_delta; + } + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + result.valid = true; + } catch (const std::exception& exception) { + result.error = "Collision trajectory validation failed: " + std::string(exception.what()); + } catch (...) { + result.error = "Collision trajectory validation callback threw an unknown exception"; + } + return result; +} + +bool CollisionChecker::initialized() const +{ + return impl_->initialized_; +} + +std::size_t CollisionChecker::dof() const +{ + return impl_->joint_names_.size(); +} + +std::size_t CollisionChecker::activePairCount() const +{ + return impl_->pairs_.size(); +} + +const std::vector& CollisionChecker::jointNames() const +{ + return impl_->joint_names_; +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp new file mode 100644 index 00000000..edc27e3e --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp @@ -0,0 +1,100 @@ +#include "algorithms/collision_detection/include/distance_sampling_policy.h" + +#include +#include +#include + +namespace cmvr { +namespace { + +void setError(std::string* error, const std::string& message) +{ + if (error) { + *error = message; + } +} + +double rotationAngle(const Eigen::Quaterniond& first, + const Eigen::Quaterniond& second) +{ + const double dot = std::clamp( + std::abs(first.normalized().dot(second.normalized())), 0.0, 1.0); + return 2.0 * std::acos(dot); +} + +} // namespace + +bool LgvDistanceSamplingPolicy::configure(const DistanceSamplingOptions& options, + std::string* error) +{ + if (!std::isfinite(options.max_geometry_displacement_m) || + options.max_geometry_displacement_m <= 0.0) { + setError(error, "max_geometry_displacement_m must be finite and positive"); + return false; + } + if (!std::isfinite(options.max_check_period_s) || + options.max_check_period_s <= 0.0) { + setError(error, "max_check_period_s must be finite and positive"); + return false; + } + options_ = options; + configured_ = true; + reset(); + if (error) { + error->clear(); + } + return true; +} + +bool LgvDistanceSamplingPolicy::shouldCheck(const std::vector& current, + const Clock::time_point now) const +{ + if (!configured_ || !has_baseline_) { + return true; + } + const double elapsed_s = std::chrono::duration(now - last_check_time_).count(); + if (elapsed_s >= options_.max_check_period_s) { + return true; + } + return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m; +} + +void LgvDistanceSamplingPolicy::markChecked(const std::vector& current, + const Clock::time_point now) +{ + last_checked_ = current; + last_check_time_ = now; + has_baseline_ = true; +} + +void LgvDistanceSamplingPolicy::reset() +{ + last_checked_.clear(); + last_check_time_ = Clock::time_point{}; + has_baseline_ = false; +} + +double LgvDistanceSamplingPolicy::displacementSinceLastCheck( + const std::vector& current) const +{ + if (!has_baseline_ || current.size() != last_checked_.size()) { + return std::numeric_limits::infinity(); + } + + double maximum_displacement = 0.0; + for (std::size_t index = 0; index < current.size(); ++index) { + const auto& previous = last_checked_[index]; + const auto& now = current[index]; + if (previous.geometry_index != now.geometry_index) { + return std::numeric_limits::infinity(); + } + const double translation = (now.position - previous.position).norm(); + const double radius = std::max(previous.bounding_radius_m, now.bounding_radius_m); + const double swept_distance = + translation + radius * rotationAngle(previous.orientation, now.orientation); + maximum_displacement = std::max(maximum_displacement, swept_distance); + } + return maximum_displacement; +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp b/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp new file mode 100644 index 00000000..3103e3f2 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp @@ -0,0 +1,840 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "algorithms/collision_detection/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "common/types/arm/arm_types.h" +#include "environment/include/robot_model.h" + +namespace cmvr { +namespace { + +const std::vector kRightArmJoints{ + "R_SHOULDER_P", + "R_SHOULDER_R", + "R_SHOULDER_Y", + "R_ELBOW_R", + "R_WRIST_P", + "R_WRIST_Y", + "R_WRIST_R", +}; + +const std::vector kGen2RightArmJoints{ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7", +}; + +const std::vector kGen2SetupPose{ + 0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0, +}; + +const std::vector kGen2WarningPose{ + 2.45028525340088, + 0.413065394330014, + -1.78610031118294, + 2.3232081721811, + -2.96828882895788, + -1.59350098130002, + 0.582912411114367, +}; + +const std::vector kGen2StopPose{ + 2.13758633436379, + 1.61835160165575, + -2.3836142221041, + 0.964538527544213, + -0.00382525077004825, + 1.74586899135531, + -0.336868659266887, +}; + +const std::vector kGen2CollisionPose{ + -0.42656969579233, + 1.41426471041774, + -2.67949400419915, + 2.45814854129954, + -2.35907388079205, + 1.14125209449898, + 1.53232912981414, +}; + +const std::vector kGen2TorsoCollisionPose{ + 1.57607137794121, + 2.06613762981425, + -1.76915077905899, + 0.959251437141443, + -0.725973209527894, + 1.79390262120717, + 0.2223354372144, +}; + +std::string collisionUrdfPath() +{ + return std::string(CMVR_ES_SOURCE_DIR) + + "/model/xiaoyan_description/dual_arm_collision.urdf"; +} + +std::string gen2CollisionUrdfPath() +{ + return std::string(CMVR_ES_SOURCE_DIR) + + "/model/gen2/collision/robot_collision.urdf"; +} + +CollisionOptions gen2CollisionOptions() +{ + CollisionOptions options; + options.ignored_pairs.push_back({"arm_link_5_2", "arm_link_7_2"}); + options.ignored_pairs.push_back({"body_link", "arm_link_2_2"}); + return options; +} + +std::vector singleBody(double x, double angle, double radius) +{ + CollisionBody body; + body.geometry_index = 1; + body.position = Eigen::Vector3d(x, 0.0, 0.0); + body.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()); + body.bounding_radius_m = radius; + return {body}; +} + +// A translated, rotated fixed frame and one moving joint make world-frame +// transforms and pairs excluded by the self-collision adjacency rules observable. +class BoxSceneUrdf { +public: + explicit BoxSceneUrdf(bool base_collision = true, + bool tip_collision = true, + double mount_x = 2.0) + { + char path[] = "/tmp/cmvr_collision_scene_XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) { + throw std::runtime_error("Failed to create collision test URDF"); + } + close(fd); + path_ = path; + std::ofstream file(path_); + file << R"()"; + if (base_collision) { + file << R"()"; + } + file << R"( + + + + + + )"; + if (tip_collision) { + file << R"()"; + } + file << R"( + + + + + )"; + } + + ~BoxSceneUrdf() + { + std::error_code error; + std::filesystem::remove(path_, error); + } + + const std::string& path() const { return path_; } + +private: + std::string path_; +}; + +BoxObstacle testBox() +{ + BoxObstacle box; + box.name = "screen"; + box.frame_id = "base"; + box.size_m = Eigen::Vector3d::Constant(0.2); + return box; +} + +CollisionOptions slideBoxOptions(double position = 2.0) +{ + auto box = testBox(); + box.frame_id = "mount"; + box.position_m.x() = position; + CollisionOptions options; + options.obstacles.push_back(box); + return options; +} + +device::JointTrajectory slideTrajectory(std::initializer_list positions) +{ + device::JointTrajectory trajectory; + for (const double position : positions) { + device::JointTrajectoryPoint point; + point.time_s = static_cast(trajectory.size()) * 0.001; + point.position = {position}; + trajectory.push_back(point); + } + return trajectory; +} + +class TemporaryUrdf { +public: + explicit TemporaryUrdf(const std::string& content) + { + char path[] = "/tmp/cmvr_test_urdf_XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) throw std::runtime_error("Failed to create test URDF"); + close(fd); + path_ = path; + std::ofstream(path_) << content; + } + ~TemporaryUrdf() + { + std::error_code error; + std::filesystem::remove(path_, error); + } + const std::string& path() const { return path_; } + +private: + std::string path_; +}; + +TEST(RobotModelTest, OptionalCollisionGeometryDoesNotInvalidateKinematics) +{ + const BoxSceneUrdf urdf(false, false); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_EQ(model.joint_names, std::vector{"slide"}); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_EQ(model.collisionGeometryCount(), 0U); + EXPECT_TRUE(model.collisionBodies({0.5}).empty()); + + // A valid URDF without collision elements remains a usable robot model. + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionBodies({0.5}).empty()); + CollisionChecker checker; + EXPECT_FALSE(checker.init(model, {"slide"}, slideBoxOptions(), &error)); + EXPECT_FALSE(error.empty()); + EXPECT_FALSE(checker.initialized()); + EXPECT_FALSE(checker.check(std::vector{0.0}).valid); +} + +TEST(RobotModelTest, SharedModelKeepsCollisionQueriesAndScenesIndependent) +{ + const BoxSceneUrdf urdf(false); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + ASSERT_TRUE(model.hasCollisionGeometry()); + EXPECT_EQ(model.collisionGeometryCount(), 1U); // Only tip has geometry. + const auto copy = model; + const auto first_bodies = model.collisionBodies({0.0}); + const auto second_bodies = copy.collisionBodies({1.0}, {"slide"}); + ASSERT_EQ(first_bodies.size(), 1U); + ASSERT_EQ(second_bodies.size(), 1U); + EXPECT_EQ(first_bodies[0].geometry, second_bodies[0].geometry); + EXPECT_EQ(first_bodies[0].link_name, "tip"); + EXPECT_EQ(first_bodies[0].joint_name, "slide"); + const auto& first_pose = first_bodies[0]; + const auto& second_pose = second_bodies[0]; + EXPECT_EQ(first_pose.geometry_index, second_pose.geometry_index); + EXPECT_TRUE(first_pose.position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + EXPECT_TRUE(second_pose.position.isApprox(Eigen::Vector3d(2.0, 1.0, 0.0), 1e-12)); + EXPECT_TRUE((second_pose.orientation * Eigen::Vector3d::UnitX()).isApprox( + Eigen::Vector3d::UnitY(), 1e-12)); + + CollisionChecker first; + CollisionChecker second; + ASSERT_TRUE(first.init(model, {"slide"}, slideBoxOptions(0.0), &error)) << error; + ASSERT_TRUE(second.init(copy, {"slide"}, slideBoxOptions(1.0), &error)) << error; + for (const double position : {0.0, 1.0, 0.0}) { + const auto first_result = first.check(std::vector{position}); + const auto second_result = second.check(std::vector{position}); + ASSERT_TRUE(first_result.valid) << first_result.error; + ASSERT_TRUE(second_result.valid) << second_result.error; + EXPECT_EQ(first_result.in_collision, position == 0.0); + EXPECT_EQ(second_result.in_collision, position == 1.0); + } + // World obstacles belong to individual checkers, never the shared model. + EXPECT_EQ(model.collisionGeometryCount(), 1U); +} + +TEST(RobotModelTest, FailedCollisionReloadClearsGeometryAndPreservesModelCopies) +{ + const BoxSceneUrdf urdf(false); + const BoxSceneUrdf incompatible(false, true, 3.0); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + const auto copy = model; + const auto bodies = model.collisionBodies({0.0}); + ASSERT_EQ(bodies.size(), 1U); + ASSERT_FALSE(model.loadCollisionGeometry(incompatible.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_EQ(model.urdfPath(), urdf.path()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionUrdfPath().empty()); + EXPECT_TRUE(copy.hasCollisionGeometry()); + EXPECT_EQ(copy.collisionUrdfPath(), urdf.path()); + EXPECT_TRUE(model.collisionBodies({0.0}).empty()); + const auto copy_bodies = copy.collisionBodies({0.0}); + ASSERT_EQ(copy_bodies.size(), 1U); + EXPECT_EQ(copy_bodies[0].geometry, bodies[0].geometry); + EXPECT_TRUE(copy_bodies[0].position.isApprox(bodies[0].position, 1e-12)); + + RobotModel other; + ASSERT_TRUE(other.loadUrdf(urdf.path())); + ASSERT_TRUE(other.loadCollisionGeometry(urdf.path())); + const auto other_bodies = other.collisionBodies({1.0}); + ASSERT_EQ(other_bodies.size(), 1U); + EXPECT_TRUE(other_bodies[0].position.isApprox(Eigen::Vector3d(2.0, 1.0, 0.0), 1e-12)); + EXPECT_TRUE(bodies[0].position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + + CollisionChecker checker; + ASSERT_TRUE(checker.init(copy, {"slide"}, slideBoxOptions(0.0), &error)) << error; + EXPECT_TRUE(checker.check(std::vector{0.0}).in_collision); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry("")); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionUrdfPath().empty()); + EXPECT_TRUE(copy.hasCollisionGeometry()); + EXPECT_TRUE(bodies[0].geometry); + EXPECT_TRUE(bodies[0].position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); +} + +TEST(RobotModelTest, CombinesProductionKinematicsAndCollisionUrdfs) +{ + struct ModelCase { + std::string kinematics_path; + std::string collision_path; + std::vector joints; + std::vector position; + CollisionOptions options; + }; + const std::string root = CMVR_ES_SOURCE_DIR; + for (const auto& test : std::vector{ + {root + "/model/xiaoyan_description/dual_arm.urdf", collisionUrdfPath(), + kRightArmJoints, std::vector(7, 0.0), {}}, + {root + "/model/gen2/robot.urdf", gen2CollisionUrdfPath(), + kGen2RightArmJoints, kGen2SetupPose, gen2CollisionOptions()}}) { + SCOPED_TRACE(test.kinematics_path); + RobotModel model; + model.joint_names = test.joints; + model.dof = test.joints.size(); + std::string error; + ASSERT_TRUE(model.loadUrdf(test.kinematics_path)); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + ASSERT_TRUE(model.loadCollisionGeometry(test.collision_path)); + EXPECT_TRUE(model.hasCollisionGeometry()); + EXPECT_GT(model.collisionGeometryCount(), 0U); + EXPECT_EQ(model.joint_names, test.joints); + CollisionChecker checker; + ASSERT_TRUE(checker.init(model, test.joints, test.options, &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + const auto model_bodies = model.collisionBodies(test.position, test.joints); + const auto checker_bodies = checker.collisionBodies(test.position); + ASSERT_EQ(model_bodies.size(), checker_bodies.size()); + for (std::size_t index = 0; index < checker_bodies.size(); ++index) { + const auto& from_model = model_bodies[index]; + const auto& from_checker = checker_bodies[index]; + EXPECT_EQ(from_model.geometry_index, from_checker.geometry_index); + EXPECT_TRUE(from_model.position.isApprox(from_checker.position, 1e-12)); + EXPECT_NEAR(from_model.orientation.angularDistance(from_checker.orientation), 0.0, 1e-12); + EXPECT_DOUBLE_EQ(from_model.bounding_radius_m, from_checker.bounding_radius_m); + } + // Compare cold distance queries: cached GJK may converge to slightly + // different values on a repeated query within its solver tolerance. + CollisionChecker bodies_checker; + ASSERT_TRUE(bodies_checker.init(model, test.joints, test.options, &error)) << error; + const auto result = checker.check(test.position); + const auto bodies_result = bodies_checker.check(model_bodies); + ASSERT_TRUE(result.valid) << result.error; + ASSERT_TRUE(bodies_result.valid) << bodies_result.error; + EXPECT_EQ(result.in_collision, bodies_result.in_collision); + EXPECT_DOUBLE_EQ(result.minimum_distance_m, bodies_result.minimum_distance_m); + } +} + +TEST(RobotModelTest, RejectsInvalidCollisionBodySelectionAndJointInput) +{ + RobotModel missing_model; + EXPECT_ANY_THROW(missing_model.collisionBodies({})); + + const BoxSceneUrdf urdf(false); + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"missing"})); + EXPECT_ANY_THROW(model.collisionBodies({0.0, 0.0}, {"slide", "slide"})); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"fixed_mount"})); + for (const auto& invalid : std::vector>{ + {}, {0.0, 1.0}, {std::numeric_limits::quiet_NaN()}, + {std::numeric_limits::infinity()}}) { + ASSERT_FALSE(model.collisionBodies({0.0}, {"slide"}).empty()); + EXPECT_ANY_THROW(model.collisionBodies(invalid, {"slide"})); + } + EXPECT_EQ(model.collisionBodies({0.25}, {"slide"}).size(), 1U); +} + +TEST(RobotModelTest, RejectsJointRequiringMultipleConfigurationCoordinates) +{ + const TemporaryUrdf urdf(R"( + + + + + + )"); + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"continuous_joint"})); +} + +TEST(RobotModelTest, ResolvesOnlyFixedFramesForWorldObstaclePlacement) +{ + const BoxSceneUrdf urdf; + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_TRUE(model.containsName("base")); + EXPECT_TRUE(model.containsName("mount")); + EXPECT_TRUE(model.containsName("fixed_mount")); + EXPECT_TRUE(model.containsName("slide")); + EXPECT_TRUE(model.containsName("tip")); + EXPECT_FALSE(model.containsName("screen")); + Eigen::Isometry3d pose; + ASSERT_TRUE(model.fixedFramePose("base", pose)); + EXPECT_TRUE(pose.matrix().isApprox(Eigen::Matrix4d::Identity(), 1e-12)); + ASSERT_TRUE(model.fixedFramePose("mount", pose)); + EXPECT_TRUE(pose.translation().isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + EXPECT_TRUE((pose.linear() * Eigen::Vector3d::UnitX()).isApprox( + Eigen::Vector3d::UnitY(), 1e-12)); + EXPECT_FALSE(model.fixedFramePose("tip", pose)); + EXPECT_FALSE(model.fixedFramePose("unknown", pose)); +} + +TEST(CollisionCheckerTest, LoadsRightArmFromDualArmUrdf) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + EXPECT_GT(checker.activePairCount(), 0U); + + const auto bodies = checker.collisionBodies(std::vector(7, 0.0)); + EXPECT_EQ(bodies.size(), 11U); + + const CollisionResult result = checker.check(bodies); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.first.rfind("L_", 0) != 0); + EXPECT_TRUE(result.second.rfind("L_", 0) != 0); +} + +TEST(CollisionCheckerTest, RejectsWrongJointVectorSize) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + + EXPECT_ANY_THROW(checker.collisionBodies(std::vector(6, 0.0))); + EXPECT_FALSE(checker.check(std::vector(6, 0.0)).valid); +} + +TEST(CollisionCheckerTest, RemovesConfiguredIgnoredPair) +{ + CollisionChecker baseline; + CollisionChecker filtered; + std::string error; + ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + + CollisionOptions options; + options.ignored_pairs.push_back({"base_link", "R_ELBOW_R_S"}); + ASSERT_TRUE(filtered.init(collisionUrdfPath(), kRightArmJoints, options, &error)) << error; + EXPECT_EQ(filtered.activePairCount() + 1, baseline.activePairCount()); +} + +TEST(CollisionCheckerTest, LoadsGen2RightArmCollisionModel) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + gen2CollisionUrdfPath(), + kGen2RightArmJoints, + gen2CollisionOptions(), + &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + EXPECT_EQ(checker.activePairCount(), 19U); + + const auto bodies = checker.collisionBodies(kGen2SetupPose); + EXPECT_EQ(bodies.size(), 8U); + + const CollisionResult setup_result = checker.check(bodies); + ASSERT_TRUE(setup_result.valid) << setup_result.error; + EXPECT_FALSE(setup_result.in_collision); + EXPECT_GT(setup_result.minimum_distance_m, 0.02); +} + +TEST(CollisionCheckerTest, ClassifiesGen2SafetyDistances) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + gen2CollisionUrdfPath(), + kGen2RightArmJoints, + gen2CollisionOptions(), + &error)) << error; + + const CollisionResult warning_result = checker.check(kGen2WarningPose); + ASSERT_TRUE(warning_result.valid) << warning_result.error; + EXPECT_FALSE(warning_result.in_collision); + EXPECT_GT(warning_result.minimum_distance_m, 0.005); + EXPECT_LE(warning_result.minimum_distance_m, 0.02); + + const CollisionResult stop_result = checker.check(kGen2StopPose); + ASSERT_TRUE(stop_result.valid) << stop_result.error; + EXPECT_FALSE(stop_result.in_collision); + EXPECT_GT(stop_result.minimum_distance_m, 0.0); + EXPECT_LE(stop_result.minimum_distance_m, 0.005); + + const CollisionResult collision_result = checker.check(kGen2CollisionPose); + ASSERT_TRUE(collision_result.valid) << collision_result.error; + EXPECT_TRUE(collision_result.in_collision); + EXPECT_LE(collision_result.minimum_distance_m, 0.0); + + const CollisionResult torso_result = + checker.check(kGen2TorsoCollisionPose); + ASSERT_TRUE(torso_result.valid) << torso_result.error; + EXPECT_TRUE(torso_result.in_collision); + EXPECT_LE(torso_result.minimum_distance_m, 0.0); + EXPECT_TRUE(torso_result.first == "body_link" || + torso_result.second == "body_link"); +} + +TEST(CollisionCheckerTest, WorldPairsIncludeStaticBaseAndFirstJointDespiteSelfFilters) +{ + const BoxSceneUrdf urdf; + CollisionOptions options; + options.ignored_pairs.push_back({"base", "tip"}); + auto box = testBox(); + options.obstacles = {box}; + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 2U); + auto result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "base"); + EXPECT_EQ(result.second, "screen"); + + options.obstacles.front().position_m.x() = 2.0; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "tip"); + + options.obstacles.front().position_m.x() = 5.0; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); + EXPECT_NEAR(result.minimum_distance_m, 2.85, 1e-6); + + // The scene is owned by the checker after initialization. + options.obstacles.front().position_m.setZero(); + EXPECT_FALSE(checker.check(std::vector{0.0}).in_collision); + + // Overlapping world boxes do not create world-world collision pairs. + box.position_m.x() = 5.0; + options.obstacles = {box, box}; + options.obstacles.back().name = "table"; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 4U); + EXPECT_FALSE(checker.check(std::vector{0.0}).in_collision); +} + +TEST(CollisionCheckerTest, RotatesBoxesInFixedFramesAndChecksExternalRobotBodies) +{ + const BoxSceneUrdf urdf(false); + CollisionOptions options; + auto box = testBox(); + box.frame_id = "mount"; + box.size_m = Eigen::Vector3d(0.6, 0.06, 0.06); + box.position_m = Eigen::Vector3d(1.0, 0.2, 0.0); + box.orientation = Eigen::AngleAxisd(std::acos(-1.0) / 2.0, Eigen::Vector3d::UnitZ()); + box.orientation.coeffs() *= 2.0; // Non-unit finite quaternions are normalized. + options.obstacles = {box}; + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 1U); + + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + auto bodies = model.collisionBodies({1.0}); + ASSERT_EQ(bodies.size(), 1U); + auto result = checker.check(bodies); // No preceding checker FK query. + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "tip"); + EXPECT_EQ(result.second, "screen"); + + bodies = checker.collisionBodies({0.0}); + EXPECT_EQ(bodies.size(), 1U); + result = checker.check(bodies); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); + EXPECT_TRUE(checker.check(std::vector{1.0}).in_collision); + + options.obstacles.front().orientation.setIdentity(); + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{1.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); +} + +TEST(CollisionCheckerTest, RejectsInvalidObstacleScenes) +{ + const BoxSceneUrdf urdf; + CollisionChecker checker; + const auto reject = [&](const BoxObstacle& box) { + CollisionOptions options; + options.obstacles = {box}; + std::string error; + EXPECT_FALSE(checker.init(urdf.path(), {"slide"}, options, &error)); + EXPECT_FALSE(error.empty()); + EXPECT_FALSE(checker.initialized()); + }; + for (const auto& name : {"", "base", "tip", "slide", "tip_0"}) { + auto box = testBox(); + box.name = name; + reject(box); + } + for (const auto& frame : {"", "missing", "tip", "slide"}) { + auto box = testBox(); + box.frame_id = frame; + reject(box); + } + for (const auto value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto box = testBox(); + box.size_m.x() = value; + reject(box); + } + auto box = testBox(); + box.position_m.y() = std::numeric_limits::infinity(); + reject(box); + box = testBox(); + box.orientation.coeffs().setZero(); + reject(box); + box.orientation.x() = std::numeric_limits::quiet_NaN(); + reject(box); + + CollisionOptions options; + options.obstacles = {testBox(), testBox()}; + std::string error; + EXPECT_FALSE(checker.init(urdf.path(), {"slide"}, options, &error)); + EXPECT_NE(error.find("unique"), std::string::npos); + EXPECT_FALSE(checker.initialized()); +} + +TEST(CollisionCheckerTest, TrajectoryRejectsObstacleBetweenValidEndpoints) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(0.0), &error)) << error; + ASSERT_TRUE(checker.isStateValid({-0.4})); + ASSERT_TRUE(checker.isStateValid({0.4})); + + const auto result = checker.checkTrajectory(slideTrajectory({-0.4, 0.4})); + EXPECT_FALSE(result.valid); + EXPECT_GT(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, TrajectoryAccumulatesShortSegmentsAcrossReversal) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + options.joint_step_rad = 0.01; + std::vector checked; + options.additional_state_valid = [&](const std::vector& q) { + checked.push_back(q[0]); + return true; + }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.006, 0.012, 0.006, 0.0}), options); + ASSERT_TRUE(result.valid) << result.error; + ASSERT_EQ(checked.size(), 4U); + EXPECT_EQ(result.validity_checks, checked.size()); + EXPECT_DOUBLE_EQ(checked[0], 0.0); + EXPECT_NEAR(checked[1], 0.01, 1e-12); + EXPECT_NEAR(checked[2], 0.004, 1e-12); + EXPECT_DOUBLE_EQ(checked[3], 0.0); +} + +TEST(CollisionCheckerTest, TrajectoryChecksEndpointEvenBelowSamplingStep) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + options.joint_step_rad = 0.02; + options.additional_state_valid = [](const std::vector& q) { return q[0] < 0.014; }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.015}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, StateAndTrajectoryShareClearanceAndAdditionalConstraints) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(0.0), &error)) << error; + CollisionValidationOptions options; + options.minimum_distance_m = 0.2; + EXPECT_FALSE(checker.isStateValid({0.3}, options)); // Physical gap is 0.15 m. + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.3, 0.4}), options).valid); + options.minimum_distance_m = 0.1; + EXPECT_TRUE(checker.isStateValid({0.3}, options)); + options.additional_state_valid = [](const std::vector& q) { + // A caller's TCP workspace constraint can reject a collision-free sample. + return q[0] <= 0.31 || q[0] >= 0.35; + }; + EXPECT_TRUE(checker.isStateValid({0.3}, options)); + EXPECT_TRUE(checker.isStateValid({0.4}, options)); + EXPECT_FALSE(checker.isStateValid({0.33}, options)); + const auto result = checker.checkTrajectory(slideTrajectory({0.3, 0.4}), options); + EXPECT_FALSE(result.valid); + EXPECT_GE(result.validity_checks, 2U); +} + +TEST(CollisionCheckerTest, TrajectoryCancellationStopsFurtherQueries) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + std::size_t checked = 0; + options.additional_state_valid = [&](const std::vector&) { + ++checked; + return true; + }; + options.is_cancelled = [] { return true; }; + auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.5}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(checked, 0U); + EXPECT_EQ(result.validity_checks, 0U); + EXPECT_FALSE(result.error.empty()); + + options.is_cancelled = [&] { return checked >= 2; }; + result = checker.checkTrajectory(slideTrajectory({0.0, 0.5}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(checked, 2U); + EXPECT_EQ(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, ValidationRejectsMalformedInputAndCallbackFailure) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + EXPECT_FALSE(checker.checkTrajectory({}).valid); + for (const auto& q : std::vector>{ + {}, {0.0, 0.0}, {std::numeric_limits::infinity()}, + {std::numeric_limits::quiet_NaN()}}) { + EXPECT_THROW(checker.isStateValid(q), std::exception); + auto trajectory = slideTrajectory({0.0, 0.001, 0.002}); + trajectory[1].position = q; + const auto result = checker.checkTrajectory(trajectory); + EXPECT_FALSE(result.valid); + EXPECT_FALSE(result.error.empty()); + } + for (const double step : {0.0, -0.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + CollisionValidationOptions options; + options.joint_step_rad = step; + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options).valid); + } + for (const double clearance : {-0.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + CollisionValidationOptions options; + options.minimum_distance_m = clearance; + EXPECT_THROW(checker.isStateValid({0.0}, options), std::exception); + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options).valid); + } + CollisionValidationOptions options; + options.additional_state_valid = [](const std::vector&) -> bool { + throw std::runtime_error("TCP constraint query failed"); + }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options); + EXPECT_FALSE(result.valid); + EXPECT_NE(result.error.find("TCP constraint query failed"), std::string::npos); +} + +TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement) +{ + LgvDistanceSamplingPolicy policy; + DistanceSamplingOptions options; + options.max_geometry_displacement_m = 0.002; + options.max_check_period_s = 0.01; + std::string error; + ASSERT_TRUE(policy.configure(options, &error)) << error; + + const auto start = LgvDistanceSamplingPolicy::Clock::now(); + const auto initial = singleBody(0.0, 0.0, 0.2); + EXPECT_TRUE(policy.shouldCheck(initial, start)); + policy.markChecked(initial, start); + + EXPECT_FALSE(policy.shouldCheck( + singleBody(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1))); + EXPECT_TRUE(policy.shouldCheck( + singleBody(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2))); + EXPECT_TRUE(policy.shouldCheck( + singleBody(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2))); + EXPECT_TRUE(policy.shouldCheck( + initial, start + std::chrono::milliseconds(10))); +} + +} // namespace +} // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt b/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt index 1ade9e29..2f2488c2 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt +++ b/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(ik_solver SHARED target_include_directories(ik_solver PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(ik_solver PUBLIC + cmvr_es::environment osqp OsqpEigen pinocchio_default diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h b/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h index bc6b0660..f8c422a8 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h @@ -6,12 +6,12 @@ #include #include #include -#include +#include #include +#include "environment/include/robot_model.h" +#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" namespace cmvr { - class UrdfParser; - class IKSolver { public: /** @@ -24,12 +24,12 @@ namespace cmvr { const std::string& base_frame_name, const std::string& tip_frame_name); /** - * @brief 构造时按外部解析器初始化链路缓存。 - * @param parser 已加载模型的 URDF 解析器。 + * @brief 构造时按已加载的机器人模型初始化链路缓存。 + * @param model 已加载运动学的机器人模型。 * @param base_frame_name 链路基座 frame 名称。 * @param tip_frame_name 链路末端 frame 名称。 */ - IKSolver(std::shared_ptr parser, + IKSolver(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name); virtual ~IKSolver()=default; @@ -86,6 +86,9 @@ namespace cmvr { */ bool getChainJointNames(std::vector& names) const; + // Shares the immutable URDF resources; metadata describes this chain. + RobotModel getRobotModel() const; + protected: /** @@ -100,21 +103,22 @@ namespace cmvr { const std::string& tip_frame_name); /** - * @brief 使用外部 UrdfParser 初始化链路信息缓存(关节限位/关节名)。 - * @param parser 已加载模型的 URDF 解析器。 + * @brief 使用 RobotModel 初始化链路信息缓存(关节限位/关节名)。 + * @param model 已加载运动学的机器人模型。 * @param base_frame_name 链路基座 frame 名称。 * @param tip_frame_name 链路末端 frame 名称。 * @return 成功返回 true,失败返回 false。 */ - bool initUrdfChain(const std::shared_ptr& parser, + bool initUrdfChain(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name); // 上次调用ik 时计算的结果 std::vector cur_joints_angle_{}; - // URDF 解析器(用于统一管理链路限位/关节名)。 - std::shared_ptr urdf_parser_{}; + // 共享只读模型;链路信息在初始化时提取一次。 + RobotModel robot_model_; + UrdfParser::ChainInfo chain_info_; // 当前缓存链路的基座 frame 名称。 std::string chain_base_frame_name_{}; @@ -131,9 +135,6 @@ namespace cmvr { // 当前缓存链路关节速度上限(rad/s, 绝对值)。 Eigen::VectorXd joint_vel_limits_{}; - // 当前缓存链路关节名称(base->tip 顺序)。 - std::vector chain_joint_names_{}; - // 链路缓存是否有效。 bool urdf_chain_cached_{false}; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h b/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h index dea8ff81..9021ba8b 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h @@ -5,16 +5,16 @@ #include #include - #include +#include "environment/include/robot_model.h" + namespace cmvr { /** - * @brief 基于 Pinocchio 的 URDF 解析工具类。 + * @brief 从已加载的 RobotModel 提取运动链信息。 * * 主要职责: - * - 加载 URDF 到 Pinocchio 模型 * - 提取 base->tip 链路信息 * - 输出链路 q/v 索引范围、关节顺序、位置/速度限位 */ @@ -64,39 +64,39 @@ public: std::vector joints; }; - /** - * @brief 加载 URDF 模型。 - * @param urdf_path URDF 文件路径。 - * @param error 可选错误信息输出。 - * @return 成功返回 true,失败返回 false。 - */ - bool loadModel(const std::string& urdf_path, std::string* error = nullptr); - /** * @brief 提取 base->tip 链路信息。 * * 实现方式:从 tip 的父关节向上回溯到 base 的父关节, * 再反转为 base->tip 顺序。 * + * @param robot_model 已加载运动学的机器人模型。 * @param base_frame_name 基坐标系 frame 名称。 * @param tip_frame_name 末端 frame 名称。 * @param out 输出链路信息。 * @param error 可选错误信息输出。 * @return 成功返回 true,失败返回 false。 */ - bool extractChain(const std::string& base_frame_name, - const std::string& tip_frame_name, - ChainInfo& out, - std::string* error = nullptr) const; - - /** @brief 获取已加载的 Pinocchio 模型。 */ - const pinocchio::Model& model() const { return model_; } - /** @brief 当前是否已成功加载模型。 */ - bool loaded() const { return loaded_; } + static bool extractChain(const RobotModel& robot_model, + const std::string& base_frame_name, + const std::string& tip_frame_name, + ChainInfo& out, + std::string* error = nullptr); + // Compatibility for linbo_dev callers that own a standalone parser. + bool loadModel(const std::string& path, std::string* error = nullptr) { + if (legacy_model_.loadUrdf(path)) return true; + if (error) *error = "failed to load URDF: " + path; + return false; + } + bool extractChain(const std::string& base, const std::string& tip, + ChainInfo& out, std::string* error = nullptr) const { + return extractChain(legacy_model_, base, tip, out, error); + } + const pinocchio::Model& model() const { return legacy_model_.kinematics(); } + bool loaded() const { return legacy_model_.hasKinematics(); } private: - pinocchio::Model model_; - bool loaded_{false}; + RobotModel legacy_model_; }; } // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp index 35918db2..ddc2def9 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp @@ -5,6 +5,7 @@ #include "algorithms/kinematics/ik_solver/common/include/ik_solver.h" #include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include "common/base/logging/logger.h" +#include namespace cmvr { @@ -16,59 +17,59 @@ IKSolver::IKSolver(const std::string& urdf_path, } } -IKSolver::IKSolver(std::shared_ptr parser, +IKSolver::IKSolver(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name) { - if (parser && !base_frame_name.empty() && !tip_frame_name.empty()) { - initUrdfChain(parser, base_frame_name, tip_frame_name); + if (model.hasKinematics() && !base_frame_name.empty() && !tip_frame_name.empty()) { + initUrdfChain(model, base_frame_name, tip_frame_name); } } bool IKSolver::initUrdfChain(const std::string& urdf_path, const std::string& base_frame_name, const std::string& tip_frame_name) { - auto parser = std::make_shared(); - std::string err; - if (!parser->loadModel(urdf_path, &err)) { - CMVR_LOG(ERROR) << "[IKSolver] Failed to load URDF: " << err; + RobotModel model; + if (!model.loadUrdf(urdf_path)) { return false; } - return initUrdfChain(parser, base_frame_name, tip_frame_name); + return initUrdfChain(model, base_frame_name, tip_frame_name); } -bool IKSolver::initUrdfChain(const std::shared_ptr& parser, +bool IKSolver::initUrdfChain(const RobotModel& source_model, const std::string& base_frame_name, const std::string& tip_frame_name) { - if (!parser) { - CMVR_LOG(ERROR) << "[IKSolver] initUrdfChain failed: parser is null"; - return false; - } - if (!parser->loaded()) { - CMVR_LOG(ERROR) << "[IKSolver] initUrdfChain failed: parser model not loaded"; - return false; - } - UrdfParser::ChainInfo chain_info; std::string err; - if (!parser->extractChain(base_frame_name, tip_frame_name, chain_info, &err)) { + if (!UrdfParser::extractChain(source_model, base_frame_name, tip_frame_name, chain_info, &err)) { CMVR_LOG(ERROR) << "[IKSolver] Failed to extract chain: " << err; return false; } - urdf_parser_ = parser; + auto model = source_model; + std::vector names; + std::vector limits; + names.reserve(chain_info.joints.size()); + limits.reserve(chain_info.joints.size()); + for (const auto& joint : chain_info.joints) { + const auto found = std::find(model.joint_names.begin(), model.joint_names.end(), joint.name); + if (found == model.joint_names.end() || model.joint_limits.size() != model.joint_names.size()) { + CMVR_LOG(ERROR) << "[IKSolver] Missing joint metadata for " << joint.name; + return false; + } + names.push_back(joint.name); + limits.push_back(model.joint_limits[std::distance(model.joint_names.begin(), found)]); + } + model.dof = names.size(); + model.joint_names = std::move(names); + model.joint_limits = std::move(limits); + chain_base_frame_name_ = base_frame_name; chain_tip_frame_name_ = tip_frame_name; - - chain_joint_names_.clear(); - joint_pos_lower_limits_ = chain_info.q_lower; joint_pos_upper_limits_ = chain_info.q_upper; joint_vel_limits_ = chain_info.v_limit; - chain_joint_names_.reserve(chain_info.joints.size()); - for (const auto& joint : chain_info.joints) { - chain_joint_names_.push_back(joint.name); - } - + chain_info_ = std::move(chain_info); + robot_model_ = std::move(model); urdf_chain_cached_ = true; return true; } @@ -92,11 +93,15 @@ bool IKSolver::getJointVelocityLimits(Eigen::VectorXd& limits) const { } bool IKSolver::getChainJointNames(std::vector& names) const { - if (!urdf_chain_cached_ || chain_joint_names_.empty()) { + if (!urdf_chain_cached_ || robot_model_.joint_names.empty()) { return false; } - names = chain_joint_names_; + names = robot_model_.joint_names; return true; } +RobotModel IKSolver::getRobotModel() const { + return robot_model_; +} + } // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp b/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp index 41a3b494..1a7d94bf 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp @@ -3,37 +3,23 @@ #include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include - -#include +#include namespace cmvr { -bool UrdfParser::loadModel(const std::string& urdf_path, std::string* error) { - try { - // 使用 Pinocchio 官方 URDF 解析入口构建模型。 - pinocchio::urdf::buildModel(urdf_path, model_); - loaded_ = true; - return true; - } catch (const std::exception& e) { - loaded_ = false; - if (error) { - *error = e.what(); - } - return false; - } -} - -bool UrdfParser::extractChain(const std::string& base_frame_name, +bool UrdfParser::extractChain(const RobotModel& robot_model, + const std::string& base_frame_name, const std::string& tip_frame_name, ChainInfo& out, - std::string* error) const { + std::string* error) { // 1) 基础合法性检查。 - if (!loaded_) { + if (!robot_model.hasKinematics()) { if (error) { *error = "model not loaded"; } return false; } + const auto& model_ = robot_model.kinematics(); if (!model_.existFrame(base_frame_name)) { if (error) { *error = "base frame not found: " + base_frame_name; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h index d9b81444..3b04c01c 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -39,9 +40,9 @@ public: const std::string& tcp_frame_name = std::string()); /** - * @brief 按外部 URDF 解析器构造。 + * @brief 按已加载的机器人模型构造。 */ - PinocchioIKBase(std::shared_ptr parser, + PinocchioIKBase(const RobotModel& model, const std::string& base_frame_name, const std::string& flange_frame_name, const std::string& tcp_frame_name = std::string()); @@ -92,7 +93,7 @@ public: bool is_tcp, Eigen::Matrix4d& pose_base, Eigen::MatrixXd& jacobian_base, - Eigen::Matrix3d& base_R_ee); + Eigen::Matrix3d& base_R_ee) const; bool computeTwistBaseAtQ(const std::vector& q_chain, const std::vector& qdot_chain, @@ -114,12 +115,27 @@ public: std::vector& qdot_out, double qdot_abs_max = std::numeric_limits::infinity()) const; + // Constrained solvers incorporate these bounds during velocity IK. Callers + // must not clip their solution afterward, which would change the TCP twist. + virtual bool supportsJointVelocityBounds() const { return false; } + virtual bool solveVelocityBase(const Eigen::MatrixXd&, + const Eigen::Matrix&, + const std::vector&, + std::vector& qdot_out, + const Eigen::VectorXd&, + const Eigen::VectorXd&, + double = std::numeric_limits::infinity()) const + { + qdot_out.clear(); + return false; + } + protected: /** * @brief 从父类缓存的 URDF 链信息初始化 Pinocchio 运行时对象与 frame 索引。 * * 调用前要求: - * - `urdf_parser_` 已有效并 loaded + * - `robot_model_` 已加载,链路信息已缓存 * - `chain_base_frame_name_` 与 `chain_tip_frame_name_` 已设置 * * @param chain_info_out 可选输出链信息(用于子类读取 q/v 区间)。 @@ -171,7 +187,7 @@ protected: static double disabledJointLimitAbs(); /** - * @brief 在当前 `model_` 上更新 FK 与 frame placement。 + * @brief 在共享模型上更新 FK 与 frame placement。 */ void updateKinematics(const Eigen::VectorXd& q_full); @@ -190,15 +206,19 @@ protected: std::string tcp_frame_name_; /** @brief Pinocchio 模型。 */ - pinocchio::Model model_; + const pinocchio::Model& model() const; /** @brief Pinocchio 运行时数据。 */ std::unique_ptr data_; + // Feedback and online planning reuse a separate workspace, serialized here. + // Never share mutable IK data_ with concurrent read-only queries. + std::unique_ptr query_data_; + mutable std::mutex query_mutex_; - /** @brief base frame 在 `model_.frames` 中的索引。 */ + /** @brief base frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex base_frame_id_{(pinocchio::FrameIndex)(-1)}; - /** @brief flange frame 在 `model_.frames` 中的索引。 */ + /** @brief flange frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex flange_frame_id_{(pinocchio::FrameIndex)(-1)}; - /** @brief tcp frame 在 `model_.frames` 中的索引。 */ + /** @brief tcp frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex tcp_frame_id_{(pinocchio::FrameIndex)(-1)}; /** @brief 是否存在有效 TCP frame。 */ bool has_tcp_{false}; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h index ffce089f..c2546591 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h @@ -45,11 +45,31 @@ public: std::vector& qdot_out, double qdot_abs_max = std::numeric_limits::infinity()) const override; + bool supportsJointVelocityBounds() const override { return true; } + + // Additional bounds are intersected with the configured joint limits. + // Both vectors may be empty when the caller has no additional constraints. + bool solveVelocityBase(const Eigen::MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const std::vector& q_chain, + std::vector& qdot_out, + const Eigen::VectorXd& lower, + const Eigen::VectorXd& upper, + double qdot_abs_max = std::numeric_limits::infinity()) const override; + // Projects a secondary joint velocity into the Cartesian task null space. static Eigen::VectorXd projectJointLimitAvoidanceToNullspace( const Eigen::MatrixXd& jacobian_base, const Eigen::VectorXd& qdot_avoid); + // Largest feasible scale in [0, 1], allowing all redundant joint motions. + // Bounds must be finite. Failure returns false and resets scale to zero. + static bool computeVelocityScale(const Eigen::MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const Eigen::VectorXd& lower, + const Eigen::VectorXd& upper, + double& scale); + /// 如你有更严格的速度 / 加速度限位,可以覆盖默认值 void setVelocityLimits(const Eigen::VectorXd &qd_max); void setAccelerationLimits(const Eigen::VectorXd &qdd_max); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp index bccc0236..3829af19 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp @@ -153,7 +153,7 @@ bool PinocchioDlsIKSolver::init() { } { - Eigen::VectorXd q0 = pinocchio::neutral(model_); + Eigen::VectorXd q0 = pinocchio::neutral(model()); updateKinematics(q0); oM_base_cached_ = data_->oMf[base_frame_id_]; base_pose_cached_ = true; @@ -165,7 +165,7 @@ bool PinocchioDlsIKSolver::init() { CMVR_LOG(INFO) << "[PinocchioDlsIKSolver] Chain '" << chain_base_frame_name_ << "' -> '" << chain_tip_frame_name_ << "': q_start=" << chain_q_start_ << " q_dof=" << chain_q_dof_ << ", v_start=" << chain_v_start_ << " v_dof=" << chain_v_dof_ - << ", nq=" << model_.nq << " nv=" << model_.nv; + << ", nq=" << model().nq << " nv=" << model().nv; CMVR_LOG(INFO) << "[PinocchioDlsIKSolver] Chain joint position limits (rad):"; for (const auto& seg : chain_info.joints) { const int q_idx = seg.q_index; @@ -203,21 +203,21 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, std::vector& joints_angle) { if (!initialized_) return false; if ((int)cur_joints_angle_.size() != chain_q_dof_) return false; - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] base frame not found: " << base_link; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] ee frame not found: " << ee_link; return false; } - const pinocchio::FrameIndex base_frame_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_frame_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_frame_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_frame_id = model().getFrameId(ee_link); - const pinocchio::JointIndex chain_base_joint = model_.frames[base_frame_id_].parent; - const pinocchio::JointIndex base_joint = model_.frames[base_frame_id].parent; - const pinocchio::JointIndex flange_joint = model_.frames[flange_frame_id_].parent; - const pinocchio::JointIndex ee_joint = model_.frames[ee_frame_id].parent; + const pinocchio::JointIndex chain_base_joint = model().frames[base_frame_id_].parent; + const pinocchio::JointIndex base_joint = model().frames[base_frame_id].parent; + const pinocchio::JointIndex flange_joint = model().frames[flange_frame_id_].parent; + const pinocchio::JointIndex ee_joint = model().frames[ee_frame_id].parent; auto jointOnParentPath = [this](pinocchio::JointIndex from, pinocchio::JointIndex target) { @@ -225,7 +225,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, pinocchio::JointIndex j = from; while (j != 0) { if (j == target) return true; - j = model_.parents[j]; + j = model().parents[j]; } return false; }; @@ -267,8 +267,8 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, break; } - Eigen::Matrix J_full(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_full(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_frame_id, pinocchio::ReferenceFrame::LOCAL, J_full); @@ -301,7 +301,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, double qdot_abs_max) { if (!initialized_) return false; - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] base frame not found: " << base_link; return false; } @@ -309,7 +309,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] ee_frame_name is empty"; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] frame not found: " << ee_link; return false; } @@ -324,13 +324,13 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, return false; } - const pinocchio::FrameIndex base_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_id = model().getFrameId(ee_link); - const pinocchio::JointIndex chain_base_joint = model_.frames[base_frame_id_].parent; - const pinocchio::JointIndex base_joint = model_.frames[base_id].parent; - const pinocchio::JointIndex flange_joint = model_.frames[flange_frame_id_].parent; - const pinocchio::JointIndex ee_joint = model_.frames[ee_id].parent; + const pinocchio::JointIndex chain_base_joint = model().frames[base_frame_id_].parent; + const pinocchio::JointIndex base_joint = model().frames[base_id].parent; + const pinocchio::JointIndex flange_joint = model().frames[flange_frame_id_].parent; + const pinocchio::JointIndex ee_joint = model().frames[ee_id].parent; auto jointOnParentPath = [this](pinocchio::JointIndex from, pinocchio::JointIndex target) { @@ -338,7 +338,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, pinocchio::JointIndex j = from; while (j != 0) { if (j == target) return true; - j = model_.parents[j]; + j = model().parents[j]; } return false; }; @@ -373,8 +373,8 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, twist_base.head<3>() = R_be * target_vel.head<3>(); twist_base.tail<3>() = R_be * target_vel.tail<3>(); - Eigen::Matrix J_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_world(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, J_world); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp index 3ceba79e..5ebec147 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp @@ -23,40 +23,33 @@ PinocchioIKBase::PinocchioIKBase(const std::string& urdf_path, , tcp_frame_name_(tcp_frame_name) { } -PinocchioIKBase::PinocchioIKBase(std::shared_ptr parser, +PinocchioIKBase::PinocchioIKBase(const RobotModel& model, const std::string& base_frame_name, const std::string& flange_frame_name, const std::string& tcp_frame_name) - : IKSolver(parser, base_frame_name, flange_frame_name) + : IKSolver(model, base_frame_name, flange_frame_name) , tcp_frame_name_(tcp_frame_name) { } bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_info_out, std::string* error) { - if (!urdf_parser_ || !urdf_parser_->loaded()) { - if (error) *error = "urdf parser not initialized"; + if (!robot_model_.hasKinematics() || !urdf_chain_cached_) { + if (error) *error = "robot model or chain is not initialized"; return false; } if (chain_base_frame_name_.empty() || chain_tip_frame_name_.empty()) { if (error) *error = "chain base/tip frame name is empty"; return false; } - if (!urdf_chain_cached_) { - if (!initUrdfChain(urdf_parser_, chain_base_frame_name_, chain_tip_frame_name_)) { - if (error) *error = "initUrdfChain failed"; - return false; - } - } + std::lock_guard query_lock(query_mutex_); + data_ = std::make_unique(model()); + query_data_ = std::make_unique(model()); - model_ = urdf_parser_->model(); - data_ = std::make_unique(model_); - - UrdfParser::ChainInfo chain_info; - std::string chain_err; - if (!urdf_parser_->extractChain(chain_base_frame_name_, chain_tip_frame_name_, chain_info, &chain_err)) { - if (error) *error = chain_err; - return false; - } + // Reinitialization starts from URDF limits before the solver reapplies its policy. + const auto& chain_info = chain_info_; + joint_pos_lower_limits_ = chain_info.q_lower; + joint_pos_upper_limits_ = chain_info.q_upper; + joint_vel_limits_ = chain_info.v_limit; base_frame_id_ = chain_info.base_frame_id; flange_frame_id_ = chain_info.tip_frame_id; @@ -67,8 +60,8 @@ bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_in has_tcp_ = false; tcp_frame_id_ = (pinocchio::FrameIndex)(-1); - if (!tcp_frame_name_.empty() && model_.existFrame(tcp_frame_name_)) { - tcp_frame_id_ = model_.getFrameId(tcp_frame_name_); + if (!tcp_frame_name_.empty() && model().existFrame(tcp_frame_name_)) { + tcp_frame_id_ = model().getFrameId(tcp_frame_name_); has_tcp_ = true; } @@ -78,20 +71,24 @@ bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_in return true; } +const pinocchio::Model& PinocchioIKBase::model() const { + return robot_model_.kinematics(); +} + bool PinocchioIKBase::buildFullQFromInput(const std::vector& joints, Eigen::VectorXd& q_full, const char* context) const { const int size = static_cast(joints.size()); - if (size != chain_q_dof_ && size != model_.nq) { + if (size != chain_q_dof_ && size != model().nq) { if (context != nullptr) { CMVR_LOG(ERROR) << "[PinocchioIKBase] " << context << " joints size mismatch"; } return false; } - q_full = pinocchio::neutral(model_); - if (size == model_.nq) { - q_full = Eigen::Map(joints.data(), model_.nq); + q_full = pinocchio::neutral(model()); + if (size == model().nq) { + q_full = Eigen::Map(joints.data(), model().nq); } else { Eigen::Map q_chain(joints.data(), chain_q_dof_); q_full.segment(chain_q_start_, chain_q_dof_) = q_chain; @@ -108,7 +105,7 @@ bool PinocchioIKBase::buildFullQFromChain(const Eigen::VectorXd& q_chain, } return false; } - q_full = pinocchio::neutral(model_); + q_full = pinocchio::neutral(model()); q_full.segment(chain_q_start_, chain_q_dof_) = q_chain; return true; } @@ -188,8 +185,8 @@ Eigen::VectorXd PinocchioIKBase::applyJointSoftLimitsToVelocity( } void PinocchioIKBase::updateKinematics(const Eigen::VectorXd& q_full) { - pinocchio::forwardKinematics(model_, *data_, q_full); - pinocchio::updateFramePlacements(model_, *data_); + pinocchio::forwardKinematics(model(), *data_, q_full); + pinocchio::updateFramePlacements(model(), *data_); } bool PinocchioIKBase::buildJacobianBaseAtQ(const std::vector& q_chain_std, @@ -217,8 +214,8 @@ bool PinocchioIKBase::buildJacobianBaseAtQ(const std::vector& q_chain_st const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; base_R_ee = base_M_ee.rotation(); - Eigen::Matrix jacobian_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix jacobian_world(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, jacobian_world); @@ -250,12 +247,12 @@ bool PinocchioIKBase::computeJacobianBaseAtQ(const std::vector& q_chain, Eigen::MatrixXd& jacobian_base, Eigen::Matrix3d& base_R_ee) { - if (!model_.existFrame(ee_frame_name)) { + if (!model().existFrame(ee_frame_name)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_frame_name; return false; } return buildJacobianBaseAtQ(q_chain, - model_.getFrameId(ee_frame_name), + model().getFrameId(ee_frame_name), jacobian_base, base_R_ee, nullptr); @@ -266,9 +263,10 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( const bool is_tcp, Eigen::Matrix4d& pose_base, Eigen::MatrixXd& jacobian_base, - Eigen::Matrix3d& base_R_ee) + Eigen::Matrix3d& base_R_ee) const { - if (!data_) { + std::lock_guard query_lock(query_mutex_); + if (!query_data_) { CMVR_LOG(ERROR) << "[PinocchioIKBase] computePoseAndJacobianBaseAtQ called before pinocchio init"; return false; } @@ -278,22 +276,27 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( } const Eigen::Map q_chain(q_chain_std.data(), chain_q_dof_); + if (!q_chain.allFinite()) return false; Eigen::VectorXd q_full; if (!buildFullQFromChain(q_chain, q_full, "computePoseAndJacobianBaseAtQ")) { return false; } - updateKinematics(q_full); + // Reuse the dedicated query workspace instead of allocating Data every cycle. + auto& query_data = *query_data_; + pinocchio::forwardKinematics(model(), query_data, q_full); + pinocchio::updateFramePlacements(model(), query_data); const pinocchio::FrameIndex ee_id = (is_tcp && has_tcp_) ? tcp_frame_id_ : flange_frame_id_; - const pinocchio::SE3& oM_base = getBasePoseWorld(); - const pinocchio::SE3& oM_ee = data_->oMf[ee_id]; + const pinocchio::SE3& oM_base = base_pose_cached_ ? oM_base_cached_ : query_data.oMf[base_frame_id_]; + const pinocchio::SE3& oM_ee = query_data.oMf[ee_id]; const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; pose_base = se3ToMatrix4(base_M_ee); base_R_ee = base_M_ee.rotation(); - Eigen::Matrix jacobian_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix jacobian_world(6, model().nv); + jacobian_world.setZero(); + pinocchio::computeFrameJacobian(model(), query_data, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, jacobian_world); @@ -304,7 +307,7 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( jacobian_base.topRows(3) = R_bo * jacobian_base.topRows(3); jacobian_base.bottomRows(3) = R_bo * jacobian_base.bottomRows(3); - return true; + return pose_base.allFinite() && jacobian_base.allFinite(); } bool PinocchioIKBase::computeMeasuredTwistBase(const std::vector& q_chain, @@ -363,13 +366,13 @@ bool PinocchioIKBase::computeTwistBaseAtQ(const std::vector& q_chain, Eigen::MatrixXd* jacobian_base_out, Eigen::Matrix3d* base_R_ee_out) { - if (!model_.existFrame(ee_frame_name)) { + if (!model().existFrame(ee_frame_name)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_frame_name; return false; } return computeMeasuredTwistBase(q_chain, qdot_chain, - model_.getFrameId(ee_frame_name), + model().getFrameId(ee_frame_name), twist_base, jacobian_base_out, base_R_ee_out, @@ -406,11 +409,11 @@ bool PinocchioIKBase::fk(const std::string& base_link, CMVR_LOG(ERROR) << "[PinocchioIKBase] fk called before pinocchio init"; return false; } - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] base frame not found: " << base_link; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_link; return false; } @@ -421,8 +424,8 @@ bool PinocchioIKBase::fk(const std::string& base_link, } updateKinematics(q_full); - const pinocchio::FrameIndex base_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_id = model().getFrameId(ee_link); const pinocchio::SE3& oM_base = data_->oMf[base_id]; const pinocchio::SE3& oM_ee = data_->oMf[ee_id]; const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp index 4825d0a5..fdaf5aea 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp @@ -60,6 +60,7 @@ namespace cmvr { std::string vectorToString(const Eigen::VectorXd& value) { std::ostringstream stream; + stream.precision(12); stream << '['; for (Eigen::Index i = 0; i < value.size(); ++i) { if (i > 0) { @@ -235,7 +236,7 @@ namespace cmvr { } initialized_ = true; - CMVR_LOG(INFO) << "[PinocchioQpIKSolver] Init OK. full nq = " << model_.nq + CMVR_LOG(INFO) << "[PinocchioQpIKSolver] Init OK. full nq = " << model().nq << ", active dof = " << chain_q_dof_ << ", q_start=" << chain_q_start_ << ", v_start=" << chain_v_start_ << ", base frame = " << chain_base_frame_name_ @@ -281,6 +282,61 @@ namespace cmvr { return nullspace * qdot_avoid; } + bool PinocchioQpIKSolver::computeVelocityScale( + const MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const VectorXd& lower, const VectorXd& upper, double& scale) + { + scale = 0.0; + const Eigen::Index dof = jacobian_base.cols(); + if (dof == 0 || jacobian_base.rows() != 6 || lower.size() != dof || + upper.size() != dof || !jacobian_base.allFinite() || + !target_twist_base.allFinite() || !lower.allFinite() || + !upper.allFinite() || (lower.array() > upper.array()).any()) { + return false; + } + + // Minimize (alpha - 1)^2 with J*qdot = alpha*target. A QP over + // qdot and alpha preserves redundancy and need not assume alpha=0 is feasible. + MatrixXd cost = MatrixXd::Zero(1, dof + 1); + cost(0, dof) = 1.0; + MatrixXd constraints = MatrixXd::Zero(dof + 7, dof + 1); + constraints.topRows(dof + 1).setIdentity(); + constraints.bottomLeftCorner(6, dof) = jacobian_base; + constraints.bottomRightCorner(6, 1) = -target_twist_base; + VectorXd constraint_lower = VectorXd::Zero(dof + 7); + VectorXd constraint_upper = VectorXd::Zero(dof + 7); + constraint_lower.head(dof) = lower; + constraint_upper.head(dof) = upper; + constraint_upper[dof] = 1.0; + + VectorXd solution; + try { + QPSolver solver; + solver.Setup(dof + 1, dof + 7, 2e-3, 1e-6, 1e-6, true); + solver.SetCostFunction(cost, VectorXd::Ones(1)); + solver.SetConstraintsFunction(constraints, constraint_lower, constraint_upper); + solution = solver.Solve(); + } catch (const std::exception&) { + return false; + } + if (solution.size() != dof + 1 || !solution.allFinite() || + (constraint_lower.head(dof + 1) - solution).maxCoeff() > 1e-6 || + (solution - constraint_upper.head(dof + 1)).maxCoeff() > 1e-6) { + return false; + } + solution = solution.cwiseMax(constraint_lower.head(dof + 1)) + .cwiseMin(constraint_upper.head(dof + 1)); + const Eigen::Matrix residual = + jacobian_base * solution.head(dof) - target_twist_base * solution[dof]; + if (!residual.allFinite() || residual.head<3>().norm() > 2e-6 || + residual.tail<3>().norm() > 2e-6) { + return false; + } + scale = solution[dof]; + return true; + } + bool PinocchioQpIKSolver::ik(const Matrix4d &target_pose, std::vector &joints_angle, bool is_tcp) { @@ -356,8 +412,8 @@ namespace cmvr { dx.tail<3>() *= w_posrot_; // 6×nv Jacobian(LOCAL) - Eigen::Matrix J_full(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_full(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, target_frame_id, pinocchio::ReferenceFrame::LOCAL, J_full); @@ -446,6 +502,20 @@ namespace cmvr { std::vector& qdot_out, const double qdot_abs_max) const { + return solveVelocityBase(jacobian_base, target_twist_base, q_chain_std, + qdot_out, VectorXd(), VectorXd(), qdot_abs_max); + } + + bool PinocchioQpIKSolver::solveVelocityBase( + const MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const std::vector& q_chain_std, + std::vector& qdot_out, + const VectorXd& external_lower, + const VectorXd& external_upper, + const double qdot_abs_max) const + { + qdot_out.clear(); if (!initialized_) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase called before init()."; return false; @@ -460,24 +530,29 @@ namespace cmvr { } const int dof = chain_v_dof_; + const bool has_external_bounds = external_lower.size() != 0 || external_upper.size() != 0; + if (has_external_bounds && + (external_lower.size() != dof || external_upper.size() != dof)) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase bounds size mismatch."; + return false; + } + const Eigen::Map q_chain(q_chain_std.data(), dof); + if (!jacobian_base.allFinite() || !target_twist_base.allFinite() || !q_chain.allFinite()) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase non-finite input."; + return false; + } const auto& avoidance = jointLimitPolicy().avoidance(); const bool use_joint_limit_avoidance = - !jointLimitsDisabled() && avoidance.enable() && avoidance.gain() > 0.0; - const int avoidance_rows = use_joint_limit_avoidance ? dof : 0; + !jointLimitsDisabled() && avoidance.enable() && avoidance.gain() > 0.0 && + target_twist_base.squaredNorm() > 1e-12; - MatrixXd cost(6 + dof + avoidance_rows, dof); - VectorXd target(6 + dof + avoidance_rows); - cost.setZero(); - target.setZero(); - cost.topRows(6) = jacobian_base; - target.head(6) = target_twist_base; - cost.middleRows(6, dof) = - std::sqrt(lambda_) * MatrixXd::Identity(dof, dof); - target.segment(6, dof).setZero(); + // The Cartesian task is a hard equality. Joint effort can only choose + // between solutions that achieve the requested twist. + const MatrixXd cost = MatrixXd::Identity(dof, dof); + VectorXd target = VectorXd::Zero(dof); VectorXd lower(dof); VectorXd upper(dof); - const Eigen::Map q_chain(q_chain_std.data(), dof); if (use_joint_limit_avoidance) { const VectorXd qdot_avoid_raw = cmvr::kinematics::computeJointLimitAvoidanceVelocity( @@ -499,9 +574,10 @@ namespace cmvr { jacobian_pinv * jacobian_base; } const VectorXd qdot_avoid_null = nullspace * qdot_avoid_raw; - cost.middleRows(6 + dof, dof) = - nullspace; - target.segment(6 + dof, dof) = qdot_avoid_null; + // With J*qdot fixed, the former secondary objective + // lambda*||qdot||^2 + ||N*qdot - qdot_avoid_null||^2 has the + // same minimizer as this centered joint-norm objective. + target = qdot_avoid_null / (1.0 + lambda_); static std::atomic avoidance_debug_counter{0}; const auto debug_index = @@ -576,19 +652,52 @@ namespace cmvr { } } } + const double policy_lower = lower[i]; + const double policy_upper = upper[i]; + if (has_external_bounds) { + if (std::isnan(external_lower[i]) || std::isnan(external_upper[i])) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase NaN joint bound."; + return false; + } + lower[i] = std::max(lower[i], external_lower[i]); + upper[i] = std::min(upper[i], external_upper[i]); + } + if (!std::isfinite(lower[i]) || !std::isfinite(upper[i]) || lower[i] > upper[i]) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase infeasible joint bounds: joint=" + << i << ", lower=" << lower[i] << ", upper=" << upper[i] + << ", q=" << q_chain[i] << ", velocity_limit=" << limit + << ", policy_lower=" << policy_lower << ", policy_upper=" << policy_upper + << ", external_lower=" << (has_external_bounds ? external_lower[i] : -std::numeric_limits::infinity()) + << ", external_upper=" << (has_external_bounds ? external_upper[i] : std::numeric_limits::infinity()); + return false; + } } + MatrixXd constraints(dof + 6, dof); + constraints.topRows(dof).setIdentity(); + constraints.bottomRows(6) = jacobian_base; + VectorXd constraint_lower(dof + 6), constraint_upper(dof + 6); + constraint_lower.head(dof) = lower; + constraint_upper.head(dof) = upper; + constraint_lower.tail(6) = target_twist_base; + constraint_upper.tail(6) = target_twist_base; + QPSolver solver; - solver.Setup(dof, dof, qp_time_limit_); + // Polish active constraints to avoid numerical violations at joint limits. + solver.Setup(dof, dof + 6, qp_time_limit_, 1e-6, 1e-6, true); solver.SetCostFunction(cost, target); - solver.SetConstraintsFunction(MatrixXd::Identity(dof, dof), lower, upper); + solver.SetConstraintsFunction(constraints, constraint_lower, constraint_upper); VectorXd qdot; try { qdot = solver.Solve(); } catch (const QPSolverException& e) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase QP failed: " - << e.what() << " (code=" << e.code() << ")"; + << e.what() << " (code=" << e.code() << ")" + << ", q=" << vectorToString(q_chain) + << ", lower=" << vectorToString(lower) + << ", upper=" << vectorToString(upper) + << ", target_twist=" << vectorToString(target_twist_base); return false; } catch (const std::exception& e) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase QP failed: " @@ -596,7 +705,26 @@ namespace cmvr { return false; } - if (qdot.size() != dof) { + if (qdot.size() != dof || !qdot.allFinite()) { + return false; + } + constexpr double kJointBoundTolerance = 1e-6; + const double bound_violation = std::max((lower - qdot).maxCoeff(), + (qdot - upper).maxCoeff()); + if (bound_violation > kJointBoundTolerance) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase joint bound residual=" + << bound_violation; + return false; + } + // Snap only violations within the solver tolerance, then verify the + // Cartesian equality again. This is not an acceleration limiter. + qdot = qdot.cwiseMax(lower).cwiseMin(upper); + const Eigen::Matrix residual = jacobian_base * qdot - target_twist_base; + constexpr double kTwistResidualTolerance = 2e-6; + if (!residual.allFinite() || residual.head<3>().norm() > kTwistResidualTolerance || + residual.tail<3>().norm() > kTwistResidualTolerance) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase Cartesian equality residual: linear=" + << residual.head<3>().norm() << ", angular=" << residual.tail<3>().norm(); return false; } qdot_out.assign(qdot.data(), qdot.data() + qdot.size()); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp index 9edbb089..a2a6005b 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp @@ -1,5 +1,7 @@ #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" +#include +#include #include #include @@ -59,6 +61,80 @@ TEST(PinocchioQpIKSolverTest, JointLimitAvoidanceIsInCartesianNullspace) EXPECT_GT(qdot_null.norm(), 0.0); } +TEST(PinocchioQpIKSolverTest, VelocityScaleUsesRedundancyAtJointLimit) +{ + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + jacobian(0, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 0.4; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.5); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.5); + upper[0] = 0.0; + + // The unconstrained least-norm solution moves joint 0 toward its limit; + // joint 6 can instead provide the entire requested Cartesian velocity. + double scale = 0.0; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 1.0, 2e-6); + + // Once the redundant joint is also constrained, the exact maximum is 25%. + upper[6] = 0.1; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 0.25, 2e-6); +} + +TEST(PinocchioQpIKSolverTest, VelocityScaleDoesNotAssumeZeroIsFeasible) +{ + const Eigen::MatrixXd jacobian = Eigen::MatrixXd::Identity(6, 6); + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 1.0; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(6, -1.0); + Eigen::VectorXd upper = Eigen::VectorXd::Ones(6); + lower[0] = 0.2; + upper[0] = 0.4; + double scale = 0.0; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 0.4, 2e-6); + + // qdot[0] must remain positive, so neither a zero nor a negative task is feasible. + for (const double velocity : {0.0, -1.0}) { + target[0] = velocity; + scale = 1.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); + } +} + +TEST(PinocchioQpIKSolverTest, VelocityScaleRejectsInvalidInputs) +{ + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Identity(6, 6); + Eigen::Matrix target = Eigen::Matrix::Zero(); + Eigen::VectorXd lower = Eigen::VectorXd::Constant(6, -1.0); + Eigen::VectorXd upper = Eigen::VectorXd::Ones(6); + double scale = 1.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian.topRows(5), target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower.head(5), upper, scale)); + lower[0] = 2.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + lower[0] = -std::numeric_limits::infinity(); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + lower[0] = -1.0; + target[0] = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); +} + TEST(PinocchioQpIKSolverTest, AvoidanceDoesNotDisturbReachableCartesianTwist) { const auto root = findProjectRoot(); @@ -97,7 +173,297 @@ TEST(PinocchioQpIKSolverTest, AvoidanceDoesNotDisturbReachableCartesianTwist) const Eigen::VectorXd achieved_enabled = jacobian * qdot_enabled_eigen; EXPECT_LT((achieved_enabled - achieved_disabled).norm(), 1e-6); - EXPECT_LT((achieved_enabled - target_twist).norm(), 5e-5); + EXPECT_LT((achieved_enabled - target_twist).norm(), 3e-6); + EXPECT_LT(qdot_enabled[6], -1e-3); + EXPECT_NEAR(qdot_disabled[6], 0.0, 1e-8); +} + +TEST(PinocchioQpIKSolverTest, TracksTouchTwistAtShoulderLimitWithoutCartesianCompromise) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + + // Reconstructed off-center touch pose: shoulder roll is at its upper limit. + const std::vector q = {0.2667416268, 1.57, 0.9599837007, 1.223555827, + -2.912197805, -0.4882931474, -0.03457454408}; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver.computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)); + Eigen::Matrix target = Eigen::Matrix::Zero(); + target.head<3>() = -0.04 * rotation.col(1); + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot)); + ASSERT_EQ(qdot.size(), q.size()); + const Eigen::Map velocity(qdot.data(), qdot.size()); + const Eigen::Matrix residual = jacobian * velocity - target; + EXPECT_LT(residual.head<3>().norm(), 2e-6); + EXPECT_LT(residual.tail<3>().norm(), 2e-6); + EXPECT_LE(qdot[1], 0.0); + EXPECT_LE(velocity.cwiseAbs().maxCoeff(), 5.0); +} + +TEST(PinocchioQpIKSolverTest, ExternalBoundsPreserveTaskAndIntersectConfiguredLimits) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + EXPECT_TRUE(solver.supportsJointVelocityBounds()); + + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + jacobian(0, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 0.04; + const std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.1); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.1); + upper[0] = 0.005; + lower[6] = 0.035; + upper[6] = 0.04; + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity - target).norm(), 2e-6); + EXPECT_LE(qdot[0], upper[0]); + EXPECT_GE(qdot[6], lower[6]); + EXPECT_LE(qdot[6], upper[6]); + + // An external bound cannot override a smaller configured velocity limit. + solver.setVelocityLimits(Eigen::VectorXd::Constant(7, 0.02)); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); +} + +TEST(PinocchioQpIKSolverTest, InfeasibleTwistFailsInsteadOfReturningSlowerOrDeflectedMotion) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + const std::vector q = {0.0, 1.57, 0.0, 1.0, 0.0, 0.0, 0.0}; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[1] = 0.04; + std::vector qdot(7, 0.1); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot)); + EXPECT_TRUE(qdot.empty()); + + target.setZero(); + target[0] = 0.04; + const Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.01); + const Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.01); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); +} + +TEST(PinocchioQpIKSolverTest, ZeroTwistStopsAvoidanceAndHonorsRemainingNullspaceDeceleration) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + auto config = loadQpConfig(root); + config.mutable_joint_limit_policy()->mutable_avoidance()->set_enable(true); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + const std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.56}; + const Eigen::Matrix target = Eigen::Matrix::Zero(); + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot)); + EXPECT_LT(Eigen::Map(qdot.data(), qdot.size()).norm(), 1e-8); + + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.1); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.1); + // Previous nullspace motion cannot stop within one acceleration-limited step. + for (const double minimum_velocity : {0.04, 0.02, 0.0}) { + lower[6] = minimum_velocity; + upper[6] = minimum_velocity + 0.01; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity).norm(), 2e-6); + EXPECT_NEAR(qdot[6], minimum_velocity, 1e-6); + EXPECT_GE(qdot[6], minimum_velocity); + } +} + +TEST(PinocchioQpIKSolverTest, InfeasibleNearLimitTwistThenHeldVelocityReproducesEmptyBounds) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + const auto config = loadQpConfig(root); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + + const auto& wrist = config.joint_limit_policy().limits().joints(6); + ASSERT_EQ(wrist.joint_name(), "R_WRIST_R"); + ASSERT_DOUBLE_EQ(wrist.q_lb(), -0.57); + ASSERT_DOUBLE_EQ(wrist.q_ub(), 1.57); + ASSERT_DOUBLE_EQ(wrist.qd(), 5.0); + ASSERT_DOUBLE_EQ(wrist.qdd(), 100.0); + const auto& soft_limit = config.joint_limit_policy().soft_limit(); + ASSERT_TRUE(soft_limit.enable()); + const double margin = std::max(soft_limit.min_margin_rad(), + soft_limit.margin_ratio() * (wrist.q_ub() - wrist.q_lb())); + ASSERT_NEAR(margin, 0.0214, 1e-12); + constexpr double dt = 0.001; + constexpr double logged_lower = -0.210923; + constexpr double logged_upper = -0.21925; + const double previous_velocity = logged_upper - wrist.qdd() * dt; + const double conflict_position = wrist.q_lb() - logged_lower * margin / wrist.qd(); + + // Constructed reproduction, not a replay of measured joint states: the log + // contains neither q nor J. This full-row-rank Jacobian makes the requested + // angular velocity uniquely require wrist velocity, isolating the conflict. + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.topLeftCorner(5, 5).setIdentity(); + jacobian(5, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[5] = previous_velocity; + std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, + conflict_position - 2.0 * previous_velocity * dt}; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -wrist.qdd() * dt); + Eigen::VectorXd upper = -lower; + lower[6] += previous_velocity; + upper[6] += previous_velocity; + const auto soft_lower = [&](double position) { + return -wrist.qd() * (position - wrist.q_lb()) / margin; + }; + + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_NEAR(qdot[6], previous_velocity, 1e-6); + + q[6] += previous_velocity * dt; + const auto first_failure_q = q; + // First failure: the joint interval is nonempty, but cannot satisfy J*qdot. + ASSERT_NEAR(soft_lower(q[6]), -0.285514121495, 1e-10); + ASSERT_LT(soft_lower(q[6]), upper[6]); + ASSERT_LT(target[5], soft_lower(q[6])); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Keeping the previous command for one more tick reproduces the reported + // empty interval. The conflict exists before considering any Cartesian task. + q[6] += previous_velocity * dt; + ASSERT_NEAR(q[6], conflict_position, 1e-12); + ASSERT_NEAR(soft_lower(q[6]), logged_lower, 1e-10); + ASSERT_NEAR(upper[6], logged_upper, 1e-12); + ASSERT_GT(soft_lower(q[6]), upper[6]); + target.setZero(); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Control: at the first failure, an achievable deceleration is still + // feasible. Applying it avoids the second failure; no limits are relaxed. + q = first_failure_q; + double reference_velocity = previous_velocity; + for (int tick = 0; tick < 4; ++tick) { + SCOPED_TRACE(tick); + lower[6] = reference_velocity - wrist.qdd() * dt; + upper[6] = reference_velocity + wrist.qdd() * dt; + target[5] = std::min(0.0, upper[6]); + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_GE(qdot[6], soft_lower(q[6]) - 1e-6); + EXPECT_LE(std::abs(qdot[6] - reference_velocity), wrist.qdd() * dt + 1e-6); + q[6] += qdot[6] * dt; + EXPECT_GT(q[6], wrist.q_lb()); + reference_velocity = qdot[6]; + } + EXPECT_NEAR(reference_velocity, 0.0, 1e-6); +} + +TEST(PinocchioQpIKSolverTest, ReplayedTouchTwistConflictsWithWristSoftLimit) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + auto config = loadQpConfig(root); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + + // Captured at the first QP failure in the MuJoCo touch replay. Unlike the + // constructed test above, the production URDF supplies the actual Jacobian. + const std::vector q = {0.582722602717, 1.18224927602, 1.476371331, + 0.30800863072, -2.97894487049, 0.408292452313, -0.568806827985}; + Eigen::Matrix target; + target << 0.0396215759735, 0.00324152795861, -0.00442980968738, 0.0, 0.0, 0.0; + Eigen::VectorXd upper(7); + upper << 0.535860147793, 0.16095635899, -0.0472852863641, + -0.602869190529, -0.0512145905955, 0.131906068524, -0.220632525731; + // Previous command +/- 100 rad/s^2 * 1 ms, before soft-limit intersection. + const Eigen::VectorXd lower = upper.array() - 0.2; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver.computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)); + const double wrist_soft_lower = -5.0 * (q[6] - (-0.57)) / 0.0214; + ASSERT_NEAR(wrist_soft_lower, -0.278778508293, 1e-9); + ASSERT_LT(wrist_soft_lower, upper[6]); + std::vector qdot; + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Diagnostic control only: source configurations remain unchanged. Keeping + // position/velocity/acceleration bounds but removing the soft margin makes + // the original Cartesian equality feasible and requires faster wrist motion. + config.mutable_joint_limit_policy()->mutable_soft_limit()->set_enable(false); + PinocchioQpIKSolver without_soft_limit(config); + ASSERT_TRUE(without_soft_limit.init()); + ASSERT_TRUE(without_soft_limit.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_LT(qdot[6], wrist_soft_lower); + RecordProperty("full_speed_wrist_without_soft_limit", std::to_string(qdot[6])); + + // Counterfactual lower speed along the same line, with all original bounds + // retained. The first feasible sample is the largest on this 0.01 grid. + double feasible_scale = 0.0; + for (int percent = 99; percent > 0; --percent) { + const double scale = percent / 100.0; + if (solver.solveVelocityBase(jacobian, scale * target, q, qdot, lower, upper)) { + feasible_scale = scale; + break; + } + } + ASSERT_GT(feasible_scale, 0.0); + ASSERT_EQ(qdot.size(), 7); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity - feasible_scale * target).norm(), 3e-6); + EXPECT_GE(qdot[6], wrist_soft_lower - 1e-6); + EXPECT_LE((velocity - upper).maxCoeff(), 1e-6); + EXPECT_LE((lower - velocity).maxCoeff(), 1e-6); + RecordProperty("largest_feasible_scale_on_percent_grid", std::to_string(feasible_scale)); + RecordProperty("scaled_wrist_with_soft_limit", std::to_string(qdot[6])); +} + +TEST(PinocchioQpIKSolverTest, PoseIkStillConvergesWithExistingConfiguration) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + const auto model = solver.getRobotModel(); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + const std::vector target_q = {0.2, 1.0, 0.8, 1.2, -2.3, -0.3, 0.2}; + Eigen::Matrix4d target_pose; + ASSERT_TRUE(solver.fk(target_q, target_pose, true)); + auto seed = target_q; + seed[0] += 0.02; + seed[3] -= 0.02; + solver.update_joints_state(seed); + std::vector result; + ASSERT_TRUE(solver.ik(target_pose, result, true)); + Eigen::Matrix4d achieved_pose; + ASSERT_TRUE(solver.fk(result, achieved_pose, true)); + EXPECT_LT((achieved_pose.block<3, 1>(0, 3) - target_pose.block<3, 1>(0, 3)).norm(), 1e-5); + EXPECT_LT((achieved_pose.block<3, 3>(0, 0) - target_pose.block<3, 3>(0, 0)).norm(), 1e-5); } } // namespace diff --git a/cmvr-es/algorithms/planner/CMakeLists.txt b/cmvr-es/algorithms/planner/CMakeLists.txt new file mode 100644 index 00000000..b7c0e35b --- /dev/null +++ b/cmvr-es/algorithms/planner/CMakeLists.txt @@ -0,0 +1,49 @@ +add_library(lgv_base_motion SHARED + cartesian/s_curve/src/s_curve_planner.cpp) +target_include_directories(lgv_base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(lgv_base_motion PUBLIC + cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common) +add_library(cmvr_es::lgv_base_motion ALIAS lgv_base_motion) +install(TARGETS lgv_base_motion LIBRARY DESTINATION lib) + +add_library(lgv_arm_motion SHARED + cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp + cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp) +target_include_directories(lgv_arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(lgv_arm_motion PUBLIC + cmvr_es::ik_solver cmvr_es::lgv_base_motion cmvr_es::curves) +add_library(cmvr_es::lgv_arm_motion ALIAS lgv_arm_motion) +add_library(cmvr_es::algorithms::lgv_arm_motion ALIAS lgv_arm_motion) +install(TARGETS lgv_arm_motion LIBRARY DESTINATION lib) + +add_library(joint_path_planner SHARED + joint/ompl/src/rrt_connect.cpp) +target_include_directories(joint_path_planner PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(joint_path_planner PUBLIC cmvr_es::proto PRIVATE ompl) +add_library(cmvr_es::joint_path_planner ALIAS joint_path_planner) +install(TARGETS joint_path_planner LIBRARY DESTINATION lib) + +add_executable(s_curve_planner_reversal_test + cartesian/s_curve/test/s_curve_planner_reversal_test.cpp) +target_link_libraries(s_curve_planner_reversal_test PRIVATE + cmvr_es::lgv_base_motion gtest gtest_main) + +add_executable(lgv_pinocchio_speedl_limits_test + cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp) +target_compile_definitions(lgv_pinocchio_speedl_limits_test PRIVATE + CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(lgv_pinocchio_speedl_limits_test PRIVATE + cmvr_es::algorithms::lgv_arm_motion gtest gtest_main) + +add_executable(rrt_connect_test + joint/ompl/test/rrt_connect_test.cpp) +target_link_libraries(rrt_connect_test PRIVATE + cmvr_es::joint_path_planner ompl gtest pthread) + +add_executable(rrt_connect_self_collision_test + joint/ompl/test/rrt_connect_self_collision_test.cpp) +target_compile_definitions(rrt_connect_self_collision_test PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(rrt_connect_self_collision_test PRIVATE + cmvr_es::joint_path_planner cmvr_es::collision_checker + ompl gtest pthread) diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h b/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h new file mode 100644 index 00000000..1cedc0f1 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h @@ -0,0 +1,64 @@ +#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H +#define CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H + +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "cmvr/config/arm_config/arm_config.pb.h" + +namespace cmvr::device { + +class CartesianMotionPlannerFactory { +public: + static std::shared_ptr createMoveL( + const config::MoveLConfig& move_l, + const std::shared_ptr& solver) + { + if (!solver) { + return nullptr; + } + switch (move_l.algorithm_case()) { + case config::MoveLConfig::kPinocchioCartesianMotionPlanner: { + auto planner = std::make_shared(solver); + if (!planner->configureMoveL(move_l.pinocchio_cartesian_motion_planner())) { + return nullptr; + } + return planner; + } + case config::MoveLConfig::ALGORITHM_NOT_SET: + default: + return nullptr; + } + } + + static std::shared_ptr createSpeedL( + const config::SpeedLConfig& speed_l, + const std::shared_ptr& solver, + std::size_t dof) + { + if (!solver) { + return nullptr; + } + switch (speed_l.algorithm_case()) { + case config::SpeedLConfig::kPinocchioCartesianMotionPlanner: { + auto planner = std::make_shared(solver); + if (!planner->configureSpeedL(speed_l.pinocchio_cartesian_motion_planner(), dof)) { + return nullptr; + } + return planner; + } + case config::SpeedLConfig::ALGORITHM_NOT_SET: + default: + return nullptr; + } + } + +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h b/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h new file mode 100644 index 00000000..557f741f --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h @@ -0,0 +1,41 @@ +#ifndef CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H +#define CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H + +#include +#include + +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +struct CartesianJointTrajectory { + std::vector> position; + std::vector> velocity; + std::vector time; + double planned_path_length{0.0}; + double executable_path_length{0.0}; + bool truncated{false}; + std::string truncation_reason; +}; + +// Offline trajectory planning, independent of online velocity state. +class CartesianTrajectoryPlanner { +public: + virtual ~CartesianTrajectoryPlanner() = default; + virtual bool configureMoveL(const config::MoveLPlannerConfig& config) = 0; + + virtual bool planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + double velocity, + double acceleration, + double jerk, + FrameType frame, + CartesianJointTrajectory& trajectory) = 0; + +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h b/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h new file mode 100644 index 00000000..6ae2a659 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h @@ -0,0 +1,62 @@ +#ifndef CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H +#define CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H + +#include +#include + +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +struct CartesianVelocityStep { + Result status{Result::failure(ArmErrorCode::RobotNotReady, "no velocity step")}; + // A valid step may be decelerating to a controlled stop. Keep executing + // successful steps and report this reason only after measured stop. + Result stop_reason{Result::success()}; + JointVelocityCommand joint_velocity; + // Smoothed Cartesian target before joint limits, not measured TCP velocity. + CartesianVelocity twist_base{}; + SpeedLReference reference{}; + // Zero target has finished decelerating, including its acceleration state. + // The executor must still check measured joint velocity before finishing. + bool settled{false}; +}; + +// Online planner. Calls are serialized by the control thread; no device I/O. +class CartesianVelocityPlanner { +public: + virtual ~CartesianVelocityPlanner() = default; + virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config, + std::size_t dof) = 0; + + // Start a new execution from feedback, discarding any interrupted command. + virtual Result reset(const std::vector& q, const std::vector& qd) = 0; + + // A valid submission replaces the target/options without resetting motion. + virtual Result submit(const CartesianVelocity& target, const SpeedLOptions& options, + FrameType frame) = 0; + // Prepare a candidate without advancing the committed planner state. A new + // step, reset or submission discards any uncommitted candidate. + // Failure returns no command. Reference is returned on the first successful + // step of a capture request; publish it only after sending the joint command. + // Apply scaling before S-curve planning; zero pauses without losing the target. + virtual CartesianVelocityStep step(double dt, const std::vector& q, + const std::vector& qd, + double speed_scaling = 1.0) = 0; + // Joint-space braking after a planning failure, without the Cartesian task + // equality. Failure means constrained braking is unavailable. + virtual CartesianVelocityStep brakeStep(double, const std::vector&, + const std::vector&) { + CartesianVelocityStep result; + result.status = Result::failure(ArmErrorCode::UnsupportedCommand, + "joint braking is not supported"); + return result; + } + // Call only after the candidate joint command was successfully submitted. + virtual void commitStep() {} +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h new file mode 100644 index 00000000..282a1161 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h @@ -0,0 +1,63 @@ +#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H +#define CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H + +#include + +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" + +namespace cmvr::device { + +class PinocchioCartesianTrajectoryPlanner final : public CartesianTrajectoryPlanner { +public: + explicit PinocchioCartesianTrajectoryPlanner(std::shared_ptr solver); + + bool configureMoveL(const config::MoveLPlannerConfig& config) override; + + bool planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + double velocity, + double acceleration, + double jerk, + FrameType frame, + CartesianJointTrajectory& trajectory) override; + +private: + bool checkMoveLPlanLineDeviation_(const Eigen::Vector3d& p_start, + const Eigen::Vector3d& line_direction, + const Eigen::Vector3d& p_current, + double traveled, + bool& deviation_warned, + bool& direction_warned, + std::string& stop_reason) const; + bool checkMoveLPlanJointContinuity_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& prev_qdot, + double dt, + double path_position, + std::string& stop_reason) const; + bool checkMoveLPlanJointPositionLimits_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + double dt, + double path_position, + std::string& stop_reason) const; + bool checkMoveLPlanCartesianStepFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + double path_position, + std::string& stop_reason) const; + + std::shared_ptr solver_{nullptr}; + config::MoveLPlannerConfig movel_config_{}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h new file mode 100644 index 00000000..13addc53 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h @@ -0,0 +1,100 @@ +#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H +#define CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H + +#include + +#include +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" + +namespace cmvr::device { + +class PinocchioCartesianVelocityPlanner final : public CartesianVelocityPlanner { +public: + explicit PinocchioCartesianVelocityPlanner(std::shared_ptr solver); + + bool configureSpeedL(const config::SpeedLPlannerConfig& config, + std::size_t dof) override; + + Result reset(const std::vector& q, const std::vector& qd) override; + Result submit(const CartesianVelocity& target, const SpeedLOptions& options, + FrameType frame) override; + CartesianVelocityStep step(double dt, const std::vector& q_measured, + const std::vector& qd_measured, + double speed_scaling = 1.0) override; + CartesianVelocityStep brakeStep(double dt, const std::vector& q, + const std::vector& qd) override; + void commitStep() override; + +private: + CartesianVelocityStep stepImpl_(double dt, const std::vector& q, + const std::vector& qd, double speed_scaling); + double adaptiveScale_(const Eigen::Matrix& target_base, + const Eigen::MatrixXd& jacobian, const std::vector& q, + const std::vector& qd, double dt); + bool updateSpeedLLimits_(const SpeedLOptions& options); + bool refreshJointAccelerationLimits_(); + Eigen::VectorXd jointAccelerationStepLimits_(Eigen::Index dof, double dt) const; + bool updateAndValidateSpeedLLineDeviation_(const Eigen::Vector3d& tcp_position, + bool is_stop_command, + const Eigen::Vector3d& command_linear_base, + const Eigen::Vector3d& target_linear_base); + bool validateSpeedLJointVelocityCommand_(const Eigen::VectorXd& qdot, + const Eigen::VectorXd& reference, + double dt) const; + bool validateSpeedLPredictedJointPositionLimits_(const std::vector& q_measured, + const Eigen::VectorXd& qdot, + double dt) const; + bool validateSpeedLCartesianVelocityFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const; + std::string describeJointLimitCandidates_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const; + + std::shared_ptr solver_{nullptr}; + config::SpeedLPlannerConfig speedl_config_{}; + struct State { + cmvr::LgvSCurvePlanner s_curve_planner_{}; + Eigen::VectorXd joint_acceleration_limits_; + std::vector prev_qdot_command_; + Eigen::Matrix speedl_command_twist_base_{Eigen::Matrix::Zero()}; + CartesianVelocity speedl_target_{}; + FrameType speedl_frame_{FrameType::Base}; + bool speedl_capture_pending_{false}; + bool speedl_command_ready_{false}; + Eigen::Vector3d speedl_line_start_tcp_base_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d speedl_line_direction_base_{Eigen::Vector3d::Zero()}; + double speedl_applied_acceleration_{0.25}; + double speedl_applied_angular_acceleration_{0.25}; + double speedl_applied_linear_jerk_{-1.0}; + bool speedl_line_check_active_{false}; + bool speedl_line_alignment_pending_{false}; + bool speedl_line_deviation_warned_{false}; + bool speedl_line_direction_warned_{false}; + + double adaptive_logged_scale{1.0}; + double adaptive_log_elapsed{0.0}; + double adaptive_scale{1.0}; + Result adaptive_stop_reason{Result::success()}; + FrameType adaptive_frame{FrameType::Base}; + Eigen::Matrix adaptive_original_target{Eigen::Matrix::Zero()}; + Eigen::Matrix adaptive_limited_target{Eigen::Matrix::Zero()}; + Eigen::Matrix adaptive_direction_base{Eigen::Matrix::Zero()}; + Eigen::VectorXd adaptive_joint_direction; + }; + State state_; + std::optional pending_; + + bool speedl_configured_{false}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp new file mode 100644 index 00000000..1fa46311 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp @@ -0,0 +1,679 @@ +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "curves/s_curve/include/s_curve.h" +#include "common/base/logging/logger.h" +#include "common/math/cartesian_motion_math.h" +#include "common/config/config_files.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { + +using cmvr::common::config::positiveOr; +using cmvr::device::cartesian_motion::clamp; +using cmvr::device::cartesian_motion::directionDeviationDeg; +using cmvr::device::cartesian_motion::lateralDistanceToLine; +using cmvr::device::cartesian_motion::rotationVector; +using cmvr::device::cartesian_motion::toEigenVector; +using cmvr::device::cartesian_motion::toStdVector; + +namespace { + +double elapsedMs(const std::chrono::steady_clock::time_point start, + const std::chrono::steady_clock::time_point end) +{ + return std::chrono::duration(end - start).count(); +} + +} // namespace + +PinocchioCartesianTrajectoryPlanner::PinocchioCartesianTrajectoryPlanner( + std::shared_ptr solver) + : solver_(std::move(solver)) +{ +} + +bool PinocchioCartesianTrajectoryPlanner::configureMoveL( + const config::MoveLPlannerConfig& config) +{ + if (!std::isfinite(config.sample_period_s()) || + !std::isfinite(config.position_gain()) || + !std::isfinite(config.rotation_gain())) { + return false; + } + movel_config_ = config; + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + const double velocity, + const double acceleration, + const double jerk, + const FrameType frame, + CartesianJointTrajectory& trajectory) +{ + const auto plan_start_time = std::chrono::steady_clock::now(); + double validation_ms = 0.0; + double current_pose_jacobian_ms = 0.0; + double solve_velocity_ms = 0.0; + double next_pose_jacobian_ms = 0.0; + std::size_t loop_count = 0; + struct PlanMoveLTimingLog { + std::chrono::steady_clock::time_point start_time; + double& validation_ms; + double& current_pose_jacobian_ms; + double& solve_velocity_ms; + double& next_pose_jacobian_ms; + std::size_t& loop_count; + CartesianJointTrajectory& trajectory; + + ~PlanMoveLTimingLog() + { + const auto end_time = std::chrono::steady_clock::now(); + const double total_ms = elapsedMs(start_time, end_time); + const double kinematics_ms = current_pose_jacobian_ms + next_pose_jacobian_ms; + const double measured_planning_ms = kinematics_ms + solve_velocity_ms; + const double planning_ms = std::max(0.0, total_ms - validation_ms); + const double misc_ms = std::max(0.0, planning_ms - measured_planning_ms); + const double loop_count_d = static_cast(loop_count); + const double per_loop_ms = loop_count_d > 0.0 ? planning_ms / loop_count_d : 0.0; + std::ostringstream oss; + oss << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] timing: total_ms=" + << total_ms + << ", planning_ms=" << planning_ms + << ", validation_ms=" << validation_ms + << ", kinematics_ms=" << kinematics_ms + << ", ik_ms=" << solve_velocity_ms + << ", misc_ms=" << misc_ms + << ", loops=" << loop_count + << ", per_loop_ms=" << per_loop_ms + << ", points=" << trajectory.position.size() + << ", planned_path_m=" << trajectory.planned_path_length + << ", executable_path_m=" << trajectory.executable_path_length + << ", truncated=" << trajectory.truncated; + if (trajectory.truncated && !trajectory.truncation_reason.empty()) { + oss << ", reason=" << trajectory.truncation_reason; + } + CMVR_LOG(INFO) << oss.str(); + } + } timing_log{plan_start_time, + validation_ms, + current_pose_jacobian_ms, + solve_velocity_ms, + next_pose_jacobian_ms, + loop_count, + trajectory}; + auto measure_validation = [&validation_ms](auto&& validator) { + const auto start_time = std::chrono::steady_clock::now(); + const bool result = validator(); + validation_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); + return result; + }; + auto measure_planning = [](double& accumulator_ms, auto&& operation) { + const auto start_time = std::chrono::steady_clock::now(); + const bool result = operation(); + accumulator_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); + return result; + }; + + trajectory = {}; + const double dt = positiveOr(movel_config_.sample_period_s(), 0.001); + if (!solver_ || q_start.empty() || + velocity <= 0.0 || acceleration <= 0.0 || jerk <= 0.0) { + return false; + } + if (static_cast(q_start.size()) != solver_->chainDof()) { + return false; + } + if (!qd_max.empty() && qd_max.size() != q_start.size()) { + return false; + } + + Eigen::Matrix4d start_pose_base = Eigen::Matrix4d::Identity(); + if (!solver_->fk(q_start, start_pose_base, true)) { + return false; + } + + const Eigen::Matrix4d target_pose_input = common::math::poseToMatrix(target); + const Eigen::Matrix4d target_pose_base = + frame == FrameType::Tool ? start_pose_base * target_pose_input : target_pose_input; + + const Eigen::Vector3d p_start = start_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d p_target = target_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d dp = p_target - p_start; + const double linear_distance = dp.norm(); + + const Eigen::Matrix3d R_start = start_pose_base.block<3, 3>(0, 0); + const Eigen::Matrix3d R_target = target_pose_base.block<3, 3>(0, 0); + const Eigen::Vector3d total_rotation_vector = rotationVector(R_target * R_start.transpose()); + const double angular_distance = total_rotation_vector.norm(); + + const double path_length = linear_distance > 1e-9 ? linear_distance : angular_distance; + trajectory.planned_path_length = path_length; + trajectory.executable_path_length = 0.0; + trajectory.position.push_back(q_start); + trajectory.velocity.push_back(std::vector(q_start.size(), 0.0)); + trajectory.time.push_back(0.0); + if (path_length <= 1e-9) { + return true; + } + + cmvr::LgvSCurve curve(velocity, acceleration, jerk); + const cmvr::LgvSCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0); + if (profile.total_time <= 0.0) { + return false; + } + const auto reserve_count = + static_cast(std::ceil(profile.total_time / dt)) + 2U; + trajectory.position.reserve(reserve_count); + trajectory.velocity.reserve(reserve_count); + trajectory.time.reserve(reserve_count); + + Eigen::VectorXd q_current = toEigenVector(q_start); + Eigen::Vector3d linear_direction = Eigen::Vector3d::Zero(); + if (linear_distance > 1e-9) { + linear_direction = dp / linear_distance; + } + const Eigen::Quaterniond q_start_rot(R_start); + const Eigen::Quaterniond q_target_rot(R_target); + const double position_gain = positiveOr(movel_config_.position_gain(), 4.0); + const double rotation_gain = positiveOr(movel_config_.rotation_gain(), 4.0); + bool line_deviation_warned = false; + bool line_direction_warned = false; + double executable_path_length = 0.0; + Eigen::VectorXd prev_qdot = Eigen::VectorXd::Zero(q_current.size()); + Eigen::Matrix4d cached_current_pose_base = Eigen::Matrix4d::Identity(); + Eigen::MatrixXd cached_current_jacobian_base; + Eigen::Matrix3d cached_current_base_R_tool = Eigen::Matrix3d::Identity(); + bool cached_current_pose_valid = false; + std::vector q_std(q_start.size(), 0.0); + std::vector q_next_std(q_start.size(), 0.0); + std::vector qdot_std(q_start.size(), 0.0); + Eigen::Matrix4d current_pose_base = Eigen::Matrix4d::Identity(); + Eigen::MatrixXd jacobian_base; + Eigen::Matrix3d base_R_tool = Eigen::Matrix3d::Identity(); + Eigen::Matrix4d next_pose_base = Eigen::Matrix4d::Identity(); + Eigen::Matrix3d next_base_R_tool = Eigen::Matrix3d::Identity(); + auto copyEigenToStdVector = [](const Eigen::VectorXd& src, std::vector& dst) { + dst.resize(static_cast(src.size())); + Eigen::Map(dst.data(), src.size()) = src; + }; + + double previous_time = 0.0; + for (double t = std::min(dt, profile.total_time); + t <= profile.total_time + 1e-9; + t = std::min(t + dt, profile.total_time)) { + ++loop_count; + const double step_dt = std::max(1e-6, t - previous_time); + previous_time = t; + + const double s = clamp(curve.getPositionAtTime(profile, t), 0.0, path_length); + const double sd = std::max(0.0, curve.getVelocityAtTime(profile, t)); + const double ratio = clamp(s / path_length, 0.0, 1.0); + + copyEigenToStdVector(q_current, q_std); + if (cached_current_pose_valid) { + current_pose_base = cached_current_pose_base; + jacobian_base.swap(cached_current_jacobian_base); + base_R_tool = cached_current_base_R_tool; + } else { + if (!measure_planning(current_pose_jacobian_ms, [&]() { + return solver_->computePoseAndJacobianBaseAtQ(q_std, + true, + current_pose_base, + jacobian_base, + base_R_tool); + })) { + return false; + } + } + + const Eigen::Vector3d p_current = current_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d p_desired = p_start + ratio * dp; + std::string stop_reason; + if (!measure_validation([&]() { + return checkMoveLPlanLineDeviation_(p_start, + linear_direction, + p_current, + (p_current - p_start).norm(), + line_deviation_warned, + line_direction_warned, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + Eigen::Matrix target_twist_base = Eigen::Matrix::Zero(); + target_twist_base.head<3>() = + linear_direction * sd + position_gain * (p_desired - p_current); + + if (angular_distance > 1e-9) { + const Eigen::Matrix3d R_current = current_pose_base.block<3, 3>(0, 0); + const Eigen::Matrix3d R_desired = + q_start_rot.slerp(ratio, q_target_rot).toRotationMatrix(); + const Eigen::Vector3d rotation_error = + rotationVector(R_desired * R_current.transpose()); + target_twist_base.tail<3>() = + (total_rotation_vector / path_length) * sd + rotation_gain * rotation_error; + } + + if (!measure_planning(solve_velocity_ms, [&]() { + return solver_->solveVelocityBase(jacobian_base, + target_twist_base, + q_std, + qdot_std, + std::numeric_limits::infinity()); + })) { + return false; + } + + Eigen::Map qdot(qdot_std.data(), + static_cast(qdot_std.size())); + Eigen::VectorXd qdot_limited = qdot; + if (!qd_max.empty()) { + double scale = 1.0; + for (Eigen::Index i = 0; i < qdot_limited.size(); ++i) { + const double limit = std::abs(qd_max[static_cast(i)]); + if (limit <= 0.0 || !std::isfinite(limit)) { + continue; + } + const double value = std::abs(qdot_limited[i]); + if (value > limit) { + scale = std::min(scale, limit / value); + } + } + qdot_limited *= scale; + } + const Eigen::Matrix achieved_twist_base = jacobian_base * qdot_limited; + if (!measure_validation([&]() { + return checkMoveLPlanCartesianStepFeasibility_(target_twist_base, + achieved_twist_base, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + const Eigen::VectorXd q_next = q_current + qdot_limited * step_dt; + if (!measure_validation([&]() { + return checkMoveLPlanJointContinuity_(q_current, + q_next, + qdot_limited, + prev_qdot, + step_dt, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + if (!measure_validation([&]() { + return checkMoveLPlanJointPositionLimits_(q_current, + q_next, + qdot_limited, + step_dt, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + + copyEigenToStdVector(q_next, q_next_std); + if (!measure_planning(next_pose_jacobian_ms, [&]() { + return solver_->computePoseAndJacobianBaseAtQ(q_next_std, + true, + next_pose_base, + cached_current_jacobian_base, + next_base_R_tool); + })) { + return false; + } + const Eigen::Vector3d p_next = next_pose_base.block<3, 1>(0, 3); + if (!measure_validation([&]() { + return checkMoveLPlanLineDeviation_(p_start, + linear_direction, + p_next, + (p_next - p_start).norm(), + line_deviation_warned, + line_direction_warned, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + + q_current = q_next; + prev_qdot = qdot_limited; + cached_current_pose_base = next_pose_base; + cached_current_base_R_tool = next_base_R_tool; + cached_current_pose_valid = true; + + trajectory.position.push_back(toStdVector(q_current)); + trajectory.velocity.push_back(toStdVector(qdot_limited)); + trajectory.time.push_back(t); + executable_path_length = s; + trajectory.executable_path_length = executable_path_length; + + if (t >= profile.total_time - 1e-9) { + break; + } + } + if (!trajectory.truncated) { + trajectory.executable_path_length = path_length; + } + + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanJointContinuity_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& prev_qdot, + const double dt, + const double path_position, + std::string& stop_reason) const +{ + const auto& config = movel_config_.joint_continuity_check(); + if (!config.enable()) { + return true; + } + if (q_current.size() != q_next.size() || + q_current.size() != qdot.size() || + qdot.size() != prev_qdot.size() || + dt <= 0.0 || !std::isfinite(dt)) { + stop_reason = "joint continuity invalid state"; + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] joint continuity invalid state"; + return false; + } + + for (Eigen::Index i = 0; i < q_next.size(); ++i) { + if (!std::isfinite(q_current[i]) || + !std::isfinite(q_next[i]) || + !std::isfinite(qdot[i]) || + !std::isfinite(prev_qdot[i])) { + std::ostringstream oss; + oss << "joint continuity non-finite value: joint_index=" << i + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] " + << stop_reason; + return false; + } + } + + const double max_delta = (q_next - q_current).cwiseAbs().maxCoeff(); + const double max_velocity = qdot.cwiseAbs().maxCoeff(); + const double max_acceleration = ((qdot - prev_qdot) / dt).cwiseAbs().maxCoeff(); + const double delta_limit = positiveOr(config.max_joint_delta_rad(), 0.05); + const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 10.0); + const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 5000.0); + + if (max_delta > delta_limit || + max_velocity > velocity_limit || + max_acceleration > acceleration_limit) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] joint continuity exceeds stop threshold: max_delta_rad=" + << max_delta << ", delta_limit_rad=" << delta_limit + << ", max_velocity_rad_s=" << max_velocity + << ", velocity_limit_rad_s=" << velocity_limit + << ", max_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "joint continuity too large: max_delta_rad=" << max_delta + << ", delta_limit_rad=" << delta_limit + << ", max_velocity_rad_s=" << max_velocity + << ", velocity_limit_rad_s=" << velocity_limit + << ", max_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanJointPositionLimits_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const double dt, + const double path_position, + std::string& stop_reason) const +{ + if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { + return true; + } + if (q_current.size() != q_next.size() || + q_current.size() != qdot.size()) { + stop_reason = "joint position limit check size mismatch"; + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] " + << stop_reason; + return false; + } + + Eigen::VectorXd lower; + Eigen::VectorXd upper; + if (!solver_->getJointPositionLimits(lower, upper) || + lower.size() != q_next.size() || + upper.size() != q_next.size()) { + return true; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + constexpr double kLimitEps = 1e-6; + for (Eigen::Index i = 0; i < q_next.size(); ++i) { + const double q = q_current[i]; + const double qn = q_next[i]; + const double lo = lower[i]; + const double hi = upper[i]; + if (!std::isfinite(q) || !std::isfinite(qn) || + !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { + continue; + } + + const bool violates_lower = qn < lo - kLimitEps; + const bool violates_upper = qn > hi + kLimitEps; + const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; + const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; + if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] predicted joint position limit exceeded: joint=" + << joint_name << ", q=" << q + << ", q_next=" << qn + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "joint position limit exceeded: joint=" << joint_name + << ", q=" << q + << ", q_next=" << qn + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanCartesianStepFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const double path_position, + std::string& stop_reason) const +{ + const auto& config = movel_config_.cartesian_step_feasibility_check(); + if (!config.enable()) { + return true; + } + + const Eigen::Vector3d desired_linear = desired_twist.head<3>(); + const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); + const double desired_linear_norm = desired_linear.norm(); + const double achieved_linear_norm = achieved_linear.norm(); + const double min_desired_linear_speed = + positiveOr(config.min_desired_linear_speed(), 1e-4); + if (desired_linear_norm >= min_desired_linear_speed) { + const double speed_ratio = achieved_linear_norm / desired_linear_norm; + const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); + const double deviation_deg = + achieved_linear_norm > 1e-9 + ? directionDeviationDeg(desired_linear, achieved_linear) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_linear_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] cartesian step infeasible after joint limits: desired_linear=[" + << desired_linear.transpose() << "], achieved_linear=[" + << achieved_linear.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "cartesian step infeasible after joint limits: linear_speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", linear_deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + + const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); + const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); + const double desired_angular_norm = desired_angular.norm(); + const double achieved_angular_norm = achieved_angular.norm(); + const double min_desired_angular_speed = + positiveOr(config.min_desired_angular_speed(), 1e-4); + if (desired_angular_norm >= min_desired_angular_speed) { + const double speed_ratio = achieved_angular_norm / desired_angular_norm; + const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); + const double deviation_deg = + achieved_angular_norm > 1e-9 + ? directionDeviationDeg(desired_angular, achieved_angular) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_angular_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] cartesian angular step infeasible after joint limits: desired_angular=[" + << desired_angular.transpose() << "], achieved_angular=[" + << achieved_angular.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "cartesian angular step infeasible after joint limits: angular_speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", angular_deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanLineDeviation_( + const Eigen::Vector3d& p_start, + const Eigen::Vector3d& line_direction, + const Eigen::Vector3d& p_current, + const double traveled, + bool& deviation_warned, + bool& direction_warned, + std::string& stop_reason) const +{ + const auto& config = movel_config_.line_deviation_check(); + if (!config.enable() || line_direction.squaredNorm() <= 1e-12) { + return true; + } + + const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); + if (traveled < min_distance) { + return true; + } + + const double lateral_error = lateralDistanceToLine(p_start, line_direction, p_current); + const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); + if (lateral_error >= stop_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line deviation exceeds stop threshold: lateral_error_m=" + << lateral_error << ", stop_m=" << stop_m + << ", traveled_m=" << traveled; + deviation_warned = true; + std::ostringstream oss; + oss << "line deviation too large: lateral_error_m=" << lateral_error + << ", stop_m=" << stop_m + << ", traveled_m=" << traveled; + stop_reason = oss.str(); + return false; + } + + const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); + if (!deviation_warned && lateral_error >= warn_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line deviation warning: lateral_error_m=" + << lateral_error << ", warn_m=" << warn_m + << ", traveled_m=" << traveled; + deviation_warned = true; + } + + const Eigen::Vector3d actual_direction = (p_current - p_start) / traveled; + const double deviation_deg = directionDeviationDeg(line_direction, actual_direction); + const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); + if (deviation_deg >= stop_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line direction deviation exceeds stop threshold: deviation_deg=" + << deviation_deg << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + direction_warned = true; + std::ostringstream oss; + oss << "line direction deviation too large: deviation_deg=" << deviation_deg + << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + stop_reason = oss.str(); + return false; + } + + const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); + if (!direction_warned && deviation_deg >= warn_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line direction deviation warning: deviation_deg=" + << deviation_deg << ", warn_deg=" << warn_deg + << ", traveled_m=" << traveled; + direction_warned = true; + } + return true; +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp new file mode 100644 index 00000000..e08eda83 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp @@ -0,0 +1,1017 @@ +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" + +#include +#include +#include +#include +#include +#include +#include +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" + +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h" +#include "common/base/logging/logger.h" +#include "common/config/config_files.h" +#include "common/math/cartesian_motion_math.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { + +using cmvr::common::config::positiveOr; +using cmvr::device::cartesian_motion::directionDeviationDeg; +using cmvr::device::cartesian_motion::lateralDistanceToLine; +using cmvr::device::cartesian_motion::toEigenVector; +using cmvr::device::cartesian_motion::toStdVector; + +PinocchioCartesianVelocityPlanner::PinocchioCartesianVelocityPlanner( + std::shared_ptr solver) + : solver_(std::move(solver)) +{ +} + +bool PinocchioCartesianVelocityPlanner::refreshJointAccelerationLimits_() +{ + if (!solver_) { + return false; + } + const auto& limits = solver_->jointLimitPolicy().limits(); + if (limits.source() != config::JOINT_LIMIT_SOURCE_CUSTOM) { + state_.joint_acceleration_limits_.resize(0); + return true; + } + + std::vector joint_names; + if (!solver_->getChainJointNames(joint_names) || joint_names.empty()) { + return false; + } + + std::unordered_map custom_limits; + custom_limits.reserve(static_cast(limits.joints_size())); + for (const auto& item : limits.joints()) { + if (!item.joint_name().empty()) { + custom_limits[item.joint_name()] = item; + } + } + + Eigen::VectorXd acceleration_limits(static_cast(joint_names.size())); + for (Eigen::Index i = 0; i < acceleration_limits.size(); ++i) { + const auto& joint_name = joint_names[static_cast(i)]; + const auto it = custom_limits.find(joint_name); + if (it == custom_limits.end() || !std::isfinite(it->second.qdd()) || it->second.qdd() < 0.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid custom qdd for " + << joint_name; + return false; + } + acceleration_limits[i] = std::abs(it->second.qdd()); + } + state_.joint_acceleration_limits_ = std::move(acceleration_limits); + return true; +} + +Eigen::VectorXd PinocchioCartesianVelocityPlanner::jointAccelerationStepLimits_( + const Eigen::Index dof, const double dt) const +{ + Eigen::VectorXd delta(dof); + for (Eigen::Index i = 0; i < dof; ++i) { + double acc_limit = 8.0; + if (state_.joint_acceleration_limits_.size() == dof && + state_.joint_acceleration_limits_[i] > 0.0) { + acc_limit = state_.joint_acceleration_limits_[i]; + } + delta[i] = acc_limit * dt; + } + return delta; +} + +bool PinocchioCartesianVelocityPlanner::configureSpeedL(const config::SpeedLPlannerConfig& config, + const std::size_t dof) +{ + if (!solver_ || dof == 0) { + return false; + } + if (!std::isfinite(config.adaptive_speed().lookahead_s()) || + config.adaptive_speed().lookahead_s() < 0.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid adaptive speed lookahead"; + return false; + } + const double min_speed_ratio = config.adaptive_speed().min_speed_ratio(); + if (!std::isfinite(min_speed_ratio) || min_speed_ratio < 0.0 || min_speed_ratio > 1.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] min_speed_ratio must be within [0, 1]"; + return false; + } + pending_.reset(); + const auto solver_dof = static_cast(std::max(0, solver_->chainVelocityDof())); + if (solver_dof != 0 && solver_dof != dof) { + return false; + } + cmvr::LgvSCurvePlanner planner; + try { + cartesian_motion::configureSCurvePlannerFromSpeedLConfig(planner, config); + } catch (const std::invalid_argument& error) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid speedL configuration: " + << error.what(); + return false; + } + + if (!refreshJointAccelerationLimits_()) { + return false; + } + + speedl_config_ = config; + state_.s_curve_planner_ = std::move(planner); + state_.speedl_applied_linear_jerk_ = -1.0; + + state_.prev_qdot_command_.assign(dof, 0.0); + state_.speedl_command_twist_base_.setZero(); + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + state_.speedl_command_ready_ = false; + state_.speedl_capture_pending_ = false; + state_.speedl_applied_acceleration_ = positiveOr(speedl_config_.linear_acceleration_max(), 5.0); + state_.speedl_applied_angular_acceleration_ = positiveOr(speedl_config_.angular_acceleration_max(), 5.0); + state_.adaptive_scale = state_.adaptive_logged_scale = 1.0; + state_.adaptive_stop_reason = Result::success(); + state_.adaptive_log_elapsed = 0.0; + state_.adaptive_joint_direction.resize(0); + speedl_configured_ = true; + return true; +} + +Result PinocchioCartesianVelocityPlanner::reset( + const std::vector& q, const std::vector& qd) +{ + pending_.reset(); + if (!solver_ || !speedl_configured_) { + return Result::failure(ArmErrorCode::RobotNotReady, "velocity planner is not configured"); + } + if (static_cast(q.size()) != solver_->chainDof() || + static_cast(qd.size()) != solver_->chainVelocityDof()) { + return Result::failure(ArmErrorCode::InvalidDof, "velocity reset state size mismatch"); + } + const auto finite = [](double value) { return std::isfinite(value); }; + if (!std::all_of(q.begin(), q.end(), finite) || !std::all_of(qd.begin(), qd.end(), finite)) { + return Result::failure(ArmErrorCode::InvalidArgument, "non-finite velocity reset state"); + } + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver_->computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation) || + jacobian.rows() != 6 || jacobian.cols() != static_cast(qd.size()) || + !jacobian.allFinite()) { + return Result::failure(ArmErrorCode::CommandFailed, "velocity reset kinematics failed"); + } + const Eigen::Matrix initial_twist = jacobian * toEigenVector(qd); + try { + // initialize() is transactional and starts with zero acceleration. + state_.s_curve_planner_.initialize(initial_twist); + } catch (const std::invalid_argument& error) { + return Result::failure(ArmErrorCode::InvalidArgument, error.what()); + } + state_.prev_qdot_command_ = qd; + state_.speedl_command_twist_base_ = initial_twist; + state_.speedl_target_ = {}; + state_.speedl_frame_ = FrameType::Base; + state_.speedl_command_ready_ = false; + state_.speedl_capture_pending_ = false; + state_.speedl_line_start_tcp_base_.setZero(); + state_.speedl_line_direction_base_.setZero(); + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + state_.adaptive_scale = state_.adaptive_logged_scale = 1.0; + state_.adaptive_stop_reason = Result::success(); + state_.adaptive_log_elapsed = 0.0; + state_.adaptive_joint_direction.resize(0); + return Result::success(); +} + +bool PinocchioCartesianVelocityPlanner::updateAndValidateSpeedLLineDeviation_( + const Eigen::Vector3d& tcp_position, + const bool is_stop_command, + const Eigen::Vector3d& command_linear_base, + const Eigen::Vector3d& target_linear_base) +{ + const auto& config = speedl_config_.line_deviation_check(); + if (!config.enable()) { + return true; + } + + const double command_norm = command_linear_base.norm(); + if (is_stop_command || command_norm <= 1e-9) { + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + return true; + } + + const Eigen::Vector3d command_direction = command_linear_base / command_norm; + const double target_norm = target_linear_base.norm(); + const bool aligned = target_norm > 1e-9 && + (command_direction - target_linear_base / target_norm).norm() <= 1e-6; + // A turn can end less than reset_deg from the last transient axis. Relatch + // once when aligned; otherwise normal straight motion accumulates false drift. + bool reset_line = !state_.speedl_line_check_active_ || (state_.speedl_line_alignment_pending_ && aligned); + state_.speedl_line_alignment_pending_ = target_norm > 1e-9 && !aligned; + if (!reset_line && state_.speedl_line_direction_base_.squaredNorm() > 1e-12) { + const double reset_deg = positiveOr(config.line_direction_reset_deg(), 10.0); + const double command_change_deg = + directionDeviationDeg(state_.speedl_line_direction_base_, command_direction); + reset_line = command_change_deg >= reset_deg; + } + + if (reset_line) { + state_.speedl_line_start_tcp_base_ = tcp_position; + state_.speedl_line_direction_base_ = command_direction; + state_.speedl_line_check_active_ = true; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + return true; + } + + const Eigen::Vector3d delta = tcp_position - state_.speedl_line_start_tcp_base_; + const double traveled = delta.norm(); + const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); + if (traveled < min_distance) { + return true; + } + + const double lateral_error = + lateralDistanceToLine(state_.speedl_line_start_tcp_base_, state_.speedl_line_direction_base_, tcp_position); + const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); + if (lateral_error >= stop_m) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] line deviation too large: lateral_error_m=" + << lateral_error << ", stop_m=" << stop_m + << ", traveled_m=" << traveled + << ", line_direction=" << state_.speedl_line_direction_base_.transpose() + << ", command_direction=" << command_direction.transpose(); + return false; + } + + const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); + if (!state_.speedl_line_deviation_warned_ && lateral_error >= warn_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][speedL] line deviation warning: lateral_error_m=" + << lateral_error << ", warn_m=" << warn_m + << ", traveled_m=" << traveled; + state_.speedl_line_deviation_warned_ = true; + } + + const Eigen::Vector3d actual_direction = delta / traveled; + const double deviation_deg = + directionDeviationDeg(state_.speedl_line_direction_base_, actual_direction); + const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); + if (deviation_deg >= stop_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] line direction deviation too large: deviation_deg=" + << deviation_deg << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + return false; + } + + const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); + if (!state_.speedl_line_direction_warned_ && deviation_deg >= warn_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][speedL] line direction deviation warning: deviation_deg=" + << deviation_deg << ", warn_deg=" << warn_deg + << ", traveled_m=" << traveled; + state_.speedl_line_direction_warned_ = true; + } + + return true; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::step( + const double dt, const std::vector& q_measured, + const std::vector& qd_measured, const double speed_scaling) +{ + pending_.reset(); + auto committed = state_; + try { + auto result = stepImpl_(dt, q_measured, qd_measured, speed_scaling); + if (result.status.ok()) pending_ = std::move(state_); + state_ = std::move(committed); + return result; + } catch (...) { + state_ = std::move(committed); + throw; + } +} + +void PinocchioCartesianVelocityPlanner::commitStep() +{ + if (!pending_) return; + const bool starting_stop = state_.adaptive_stop_reason.ok() && !pending_->adaptive_stop_reason.ok(); + state_ = std::move(*pending_); + pending_.reset(); + if (starting_stop) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][ADAPTIVE_SPEED_STOP] " + << state_.adaptive_stop_reason.message << "; decelerating through S-curve"; + } + const double scale = state_.adaptive_scale; + const bool entering = scale < 0.999 && state_.adaptive_logged_scale >= 0.999; + const bool restoring = scale >= 0.999 && state_.adaptive_logged_scale < 0.999; + const bool stopping = scale == 0.0 && state_.adaptive_logged_scale > 0.0; + const bool changed = std::abs(scale - state_.adaptive_logged_scale) >= 0.01 && + state_.adaptive_log_elapsed >= 0.1; + if (speedl_config_.adaptive_speed().enable() && (entering || restoring || stopping || changed)) { + const auto& original = state_.adaptive_original_target; + const auto& limited = state_.adaptive_limited_target; + CMVR_LOG(INFO) << "[PinocchioCartesianVelocityPlanner][ADAPTIVE_SPEED]" + << " frame=" << (state_.adaptive_frame == FrameType::Tool ? "Tool" : "Base") + << ", original_target=[" << original.transpose() << "]" + << ", reduction_percent=" << (1.0 - scale) * 100.0 + << ", limited_target=[" << limited.transpose() << "]" + << ", original_linear_m_s=" << original.head<3>().norm() + << ", limited_linear_m_s=" << limited.head<3>().norm() + << ", original_angular_rad_s=" << original.tail<3>().norm() + << ", limited_angular_rad_s=" << limited.tail<3>().norm() + << ", planned_linear_m_s=" << state_.speedl_command_twist_base_.head<3>().norm() + << ", planned_angular_rad_s=" << state_.speedl_command_twist_base_.tail<3>().norm(); + state_.adaptive_logged_scale = scale; + state_.adaptive_log_elapsed = 0.0; + } +} + +double PinocchioCartesianVelocityPlanner::adaptiveScale_( + const Eigen::Matrix& target_base, const Eigen::MatrixXd& jacobian, + const std::vector& q, const std::vector& qd, const double dt) +{ + if (!speedl_config_.adaptive_speed().enable() || target_base.squaredNorm() < 1e-12 || + !solver_->jointLimitPolicy().limits().enable()) return 1.0; + // The preview QP keeps redundancy available while finding a feasible target + // scale. Its future-target bounds deliberately exclude one-step acceleration; + // the S-curve and final command QP enforce the actual next-step constraints. + Eigen::VectorXd lower, upper, velocity; + const Eigen::Index dof = static_cast(q.size()); + if (!solver_->getJointPositionLimits(lower, upper) || !solver_->getJointVelocityLimits(velocity) || + lower.size() != dof || upper.size() != dof || velocity.size() != dof || + !lower.allFinite() || !upper.allFinite() || !velocity.allFinite() || + (lower.array() >= upper.array()).any()) return std::numeric_limits::quiet_NaN(); + double horizon = std::max(positiveOr(speedl_config_.adaptive_speed().lookahead_s(), 0.15), 2.0 * dt); + // Keep at least the current S-curve stopping duration as preview time. + // Joint jerk is not inferred from Cartesian jerk; joint braking is checked separately. + const auto& curve = state_.s_curve_planner_; + for (int offset : {0, 3}) { + const double speed = curve.getTwistBase().segment<3>(offset).norm(); + const double acceleration = curve.getAccelerationBase().segment<3>(offset).norm(); + const double a_max = offset == 0 ? state_.speedl_applied_acceleration_ : state_.speedl_applied_angular_acceleration_; + const double j_max = offset == 0 ? positiveOr(state_.speedl_applied_linear_jerk_, 10.0) + : positiveOr(speedl_config_.angular_jerk_max(), 12.0); + const auto stop = LgvSCurve(speed + acceleration * acceleration / (2.0 * j_max) + 1.0, a_max, j_max).calculateVelocityProfile( + speed, 0.0, std::min(acceleration, a_max)); + if (stop.valid) horizon = std::max(horizon, stop.total_time + 2.0 * dt); + } + const auto delta = jointAccelerationStepLimits_(dof, dt); + Eigen::VectorXd preview_lower(dof), preview_upper(dof); + const auto& soft = solver_->jointLimitPolicy().soft_limit(); + for (Eigen::Index i = 0; i < dof; ++i) { + const double previous = state_.prev_qdot_command_[i]; + const double positive_speed = std::max({0.0, qd[i], previous}); + const double negative_speed = std::max({0.0, -qd[i], -previous}); + const double acceleration = delta[i] / dt; + const double lower_reserve = negative_speed * dt + negative_speed * negative_speed / (2.0 * acceleration); + const double upper_reserve = positive_speed * dt + positive_speed * positive_speed / (2.0 * acceleration); + // Stay inside the solver's 1e-6 hard-limit clamp, including roundoff. + const double lower_distance = std::max(0.0, q[i] - lower[i] - 2e-6); + const double upper_distance = std::max(0.0, upper[i] - q[i] - 2e-6); + preview_lower[i] = -std::min(std::abs(velocity[i]), std::max(0.0, lower_distance - lower_reserve) / horizon); + preview_upper[i] = std::min(std::abs(velocity[i]), std::max(0.0, upper_distance - upper_reserve) / horizon); + if (soft.enable()) { + const double margin = std::max(positiveOr(soft.min_margin_rad(), 0.02), + positiveOr(soft.margin_ratio(), 0.08) * (upper[i] - lower[i])); + preview_lower[i] = std::max(preview_lower[i], -std::abs(velocity[i]) * std::min(1.0, lower_distance / margin)); + preview_upper[i] = std::min(preview_upper[i], std::abs(velocity[i]) * std::min(1.0, upper_distance / margin)); + } + } + double scale = 0.0; + if (!PinocchioQpIKSolver::computeVelocityScale(jacobian, target_base, preview_lower, preview_upper, scale)) { + return std::numeric_limits::quiet_NaN(); + } + // The preview QP may use a different redundant-joint allocation from the + // command QP. During straight motion also predict from the allocation that + // was actually sent, so a theoretical nullspace solution cannot postpone + // deceleration until the currently moving joint reaches its limit. + const auto& current = state_.speedl_command_twist_base_; + const double projection = current.dot(target_base) / target_base.squaredNorm(); + const auto direction = target_base.normalized().eval(); + if (current.norm() >= 1e-4 && projection > 0.0 && + (current - projection * target_base).norm() <= 1e-3 * current.norm()) { + state_.adaptive_joint_direction = toEigenVector(state_.prev_qdot_command_) / current.norm(); + state_.adaptive_direction_base = direction; + } + // Keep the last resolved direction when almost stopped; dividing numerical + // IK residuals by a vanishing TCP speed would otherwise restart acceleration. + if (state_.adaptive_joint_direction.size() == dof && + (direction - state_.adaptive_direction_base).norm() <= 1e-3) { + for (Eigen::Index i = 0; i < dof; ++i) { + const double predicted = state_.adaptive_joint_direction[i] * target_base.norm(); + if (predicted > 1e-9) scale = std::min(scale, preview_upper[i] / predicted); + if (predicted < -1e-9) scale = std::min(scale, preview_lower[i] / predicted); + } + } + return scale >= 1.0 - 1e-6 ? 1.0 : scale; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::brakeStep( + const double dt, const std::vector& q, const std::vector& qd) +{ + pending_.reset(); + CartesianVelocityStep result; + const auto finite = [](double value) { return std::isfinite(value); }; + if (!solver_ || !speedl_configured_ || !std::isfinite(dt) || dt < 1e-9 || + q.size() != static_cast(solver_->chainDof()) || qd.size() != q.size() || + state_.prev_qdot_command_.size() != q.size() || + !std::all_of(q.begin(), q.end(), finite) || !std::all_of(qd.begin(), qd.end(), finite)) { + result.status = Result::failure(ArmErrorCode::InvalidArgument, "invalid joint braking state"); + return result; + } + const auto delta = jointAccelerationStepLimits_(q.size(), dt); + Eigen::VectorXd lower, upper, velocity; + const bool bounded = solver_->jointLimitPolicy().limits().enable(); + if (bounded && (!solver_->getJointPositionLimits(lower, upper) || + !solver_->getJointVelocityLimits(velocity) || lower.size() != static_cast(q.size()) || + upper.size() != lower.size() || velocity.size() != lower.size())) { + result.status = Result::failure(ArmErrorCode::InvalidArgument, "invalid joint braking limits"); + return result; + } + result.joint_velocity.velocity.resize(q.size()); + result.settled = true; + for (std::size_t i = 0; i < q.size(); ++i) { + double lo = std::max(qd[i], state_.prev_qdot_command_[i]) - delta[i]; + double hi = std::min(qd[i], state_.prev_qdot_command_[i]) + delta[i]; + if (bounded) { + lo = std::max(lo, -std::abs(velocity[i])); + hi = std::min(hi, std::abs(velocity[i])); + } + if (lo > hi) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "joint braking acceleration bounds conflict"); + result.joint_velocity.velocity.clear(); + return result; + } + const double command = std::clamp(0.0, lo, hi); + const double stop_distance = std::abs(command) * dt + command * command / (2.0 * (delta[i] / dt)); + const double furthest = q[i] + std::copysign(stop_distance, command); + if (bounded && (q[i] < lower[i] - 1e-6 || q[i] > upper[i] + 1e-6 || + furthest < lower[i] - 1e-6 || furthest > upper[i] + 1e-6)) { + result.status = Result::failure(ArmErrorCode::OutOfJointLimit, "joint braking would cross hard position limit"); + result.joint_velocity.velocity.clear(); + return result; + } + result.joint_velocity.velocity[i] = command; + result.settled = result.settled && std::abs(command) < 1e-9; + } + pending_ = state_; + pending_->prev_qdot_command_ = result.joint_velocity.velocity; + pending_->speedl_command_twist_base_.setZero(); + result.status = Result::success(); + return result; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::stepImpl_( + const double dt, const std::vector& q_measured, + const std::vector& qd_measured, const double speed_scaling) +{ + auto failure = [](ArmErrorCode code, const char* message) { + CartesianVelocityStep result; + result.status = Result::failure(code, message); + return result; + }; + if (!solver_ || !speedl_configured_ || !state_.speedl_command_ready_) { + return failure(ArmErrorCode::RobotNotReady, "velocity planner has no submitted command"); + } + if (!std::isfinite(dt) || dt <= 0.0) { + return failure(ArmErrorCode::InvalidArgument, "invalid velocity planning period"); + } + if (!std::isfinite(speed_scaling) || speed_scaling < 0.0 || speed_scaling > 1.0) { + return failure(ArmErrorCode::InvalidArgument, "speed scaling must be finite and within [0, 1]"); + } + if (static_cast(q_measured.size()) != solver_->chainDof() || + static_cast(qd_measured.size()) != solver_->chainVelocityDof()) { + return failure(ArmErrorCode::InvalidDof, "velocity planning state size mismatch"); + } + const auto finite = [](double value) { return std::isfinite(value); }; + if (!std::all_of(q_measured.begin(), q_measured.end(), finite) || + !std::all_of(qd_measured.begin(), qd_measured.end(), finite)) { + return failure(ArmErrorCode::InvalidArgument, "non-finite velocity planning state"); + } + + Eigen::Matrix4d tcp_pose_base; + Eigen::MatrixXd jacobian_base; + Eigen::Matrix3d base_R_tool; + if (!solver_->computePoseAndJacobianBaseAtQ(q_measured, true, tcp_pose_base, + jacobian_base, base_R_tool) || + !tcp_pose_base.allFinite() || !jacobian_base.allFinite()) { + return failure(ArmErrorCode::CommandFailed, "velocity planning kinematics failed"); + } + if (state_.speedl_frame_ == FrameType::Tool && !base_R_tool.allFinite()) { + return failure(ArmErrorCode::InvalidArgument, "non-finite Tool rotation"); + } + + const auto target_twist = common::math::velocityToVector(state_.speedl_target_); + bool is_stop_command = target_twist.squaredNorm() <= 1e-12; + auto plan_target = target_twist; + const double linear_limit = positiveOr(speedl_config_.linear_velocity_max(), .55); + const double angular_limit = positiveOr(speedl_config_.angular_velocity_max(), 1.0); + if (plan_target.head<3>().norm() > linear_limit) { + plan_target.head<3>() *= linear_limit / plan_target.head<3>().norm(); + } + if (plan_target.tail<3>().norm() > angular_limit) { + plan_target.tail<3>() *= angular_limit / plan_target.tail<3>().norm(); + } + plan_target *= speed_scaling; + state_.adaptive_original_target = plan_target; + state_.adaptive_frame = state_.speedl_frame_; + auto base_target = plan_target; + if (state_.speedl_frame_ == FrameType::Tool) { + base_target.head<3>() = base_R_tool * plan_target.head<3>(); + base_target.tail<3>() = base_R_tool * plan_target.tail<3>(); + } + if (state_.adaptive_stop_reason.ok()) { + state_.adaptive_scale = adaptiveScale_(base_target, jacobian_base, q_measured, qd_measured, dt); + if (!std::isfinite(state_.adaptive_scale)) { + return failure(ArmErrorCode::CommandFailed, "adaptive speed feasibility preview failed"); + } + const double min_ratio = speedl_config_.adaptive_speed().min_speed_ratio(); + if (speedl_config_.adaptive_speed().enable() && min_ratio > 0.0 && + base_target.squaredNorm() > 1e-12 && state_.adaptive_scale < min_ratio) { + std::ostringstream reason; + reason << "adaptive speed ratio below min_speed_ratio: allowed_ratio=" << state_.adaptive_scale + << ", min_speed_ratio=" << min_ratio + << ", original_linear_m_s=" << plan_target.head<3>().norm() + << ", original_angular_rad_s=" << plan_target.tail<3>().norm(); + state_.adaptive_stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, reason.str()); + } + // Preserve the previous near-zero hold behavior when the percentage + // threshold is disabled. Never quantize the ratio before comparing it. + if (min_ratio == 0.0 && state_.adaptive_scale < 1.0 && + state_.adaptive_scale * base_target.head<3>().norm() < + positiveOr(speedl_config_.linear_target_replan_threshold(), 1e-4) && + state_.adaptive_scale * base_target.tail<3>().norm() < + positiveOr(speedl_config_.angular_target_replan_threshold(), 1e-4)) { + state_.adaptive_scale = 0.0; + } + } + if (!state_.adaptive_stop_reason.ok()) { + // Finish the accepted S-curve stop even if feasibility subsequently + // improves. The executor publishes the reason after measured stop. + state_.adaptive_scale = 0.0; + is_stop_command = true; + } + plan_target *= state_.adaptive_scale; + state_.adaptive_limited_target = plan_target; + state_.adaptive_log_elapsed += dt; + try { + if (is_stop_command) { + plan_target.setZero(); + } + + state_.speedl_command_twist_base_ = state_.s_curve_planner_.plan( + plan_target, state_.speedl_frame_ == FrameType::Tool ? LgvCartesianFrame::Tool : LgvCartesianFrame::Base, + dt, base_R_tool); + } catch (const std::invalid_argument& error) { + return failure(ArmErrorCode::InvalidArgument, error.what()); + } catch (const std::runtime_error& error) { + return failure(ArmErrorCode::CommandFailed, error.what()); + } + Eigen::Vector3d target_linear_base = target_twist.head<3>(); + if (state_.speedl_frame_ == FrameType::Tool) target_linear_base = base_R_tool * target_linear_base.eval(); + if (!updateAndValidateSpeedLLineDeviation_(tcp_pose_base.block<3, 1>(0, 3), + is_stop_command, + state_.speedl_command_twist_base_.head<3>(), + target_linear_base)) { + return failure(ArmErrorCode::OutOfWorkspace, "velocity planning line deviation exceeded"); + } + + const Eigen::VectorXd reference = toEigenVector( + state_.prev_qdot_command_.size() == q_measured.size() ? state_.prev_qdot_command_ : qd_measured); + const bool limit_acceleration = !speedl_config_.has_enforce_joint_acceleration_limits() || + speedl_config_.enforce_joint_acceleration_limits(); + Eigen::VectorXd lower = Eigen::VectorXd::Constant(reference.size(), + -std::numeric_limits::infinity()); + Eigen::VectorXd upper = -lower; + if (limit_acceleration) { + const Eigen::VectorXd delta = jointAccelerationStepLimits_(reference.size(), dt); + lower = reference - delta; + upper = reference + delta; + } + Eigen::VectorXd qdot = Eigen::VectorXd::Zero(reference.size()); + const bool stopped_profile = !state_.s_curve_planner_.isMoving() && + state_.speedl_command_twist_base_.squaredNorm() <= 1e-12; + if (solver_->supportsJointVelocityBounds()) { + if (solver_->jointLimitPolicy().limits().enable()) { + Eigen::VectorXd position_lower, position_upper; + if (!solver_->getJointPositionLimits(position_lower, position_upper) || + position_lower.size() != reference.size() || + position_upper.size() != reference.size()) { + return failure(ArmErrorCode::InvalidArgument, "invalid joint position limits"); + } + const Eigen::VectorXd q = toEigenVector(q_measured); + lower = lower.cwiseMax((position_lower - q) / dt); + upper = upper.cwiseMin((position_upper - q) / dt); + } + // Also solve zero targets with acceleration bounds, so a stopped + // Cartesian profile cannot abruptly discard remaining joint motion. + std::vector qdot_std; + if (!solver_->solveVelocityBase(jacobian_base, state_.speedl_command_twist_base_, q_measured, + qdot_std, lower, upper)) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][SPEEDL_QP_STATE] dt=" << dt + << ", q=[" << toEigenVector(q_measured).transpose() << "]" + << ", measured_qd=[" << toEigenVector(qd_measured).transpose() << "]" + << ", previous_command=[" << reference.transpose() << "]" + << ", external_lower=[" << lower.transpose() << "]" + << ", external_upper=[" << upper.transpose() << "]"; + return failure(ArmErrorCode::CommandFailed, + "Cartesian velocity is infeasible within joint limits"); + } + qdot = toEigenVector(qdot_std); + } else { + // DLS retains its existing acceleration limiting behavior. + if (!stopped_profile) { + std::vector qdot_std; + if (!solver_->solveVelocityBase(jacobian_base, state_.speedl_command_twist_base_, q_measured, + qdot_std, std::numeric_limits::infinity())) { + return failure(ArmErrorCode::CommandFailed, "velocity IK failed"); + } + qdot = toEigenVector(qdot_std); + } + if (limit_acceleration) qdot = qdot.cwiseMax(lower).cwiseMin(upper); + } + const Eigen::Matrix achieved_twist_base = jacobian_base * qdot; + // A near-zero stop command cannot define a meaningful direction/speed ratio. + if (!is_stop_command && speed_scaling > 0.0 && + !validateSpeedLCartesianVelocityFeasibility_(state_.speedl_command_twist_base_, + achieved_twist_base, + toEigenVector(q_measured), qdot)) { + return failure(ArmErrorCode::CommandFailed, "Cartesian velocity is infeasible after joint limits"); + } + if (!validateSpeedLJointVelocityCommand_(qdot, reference, dt)) { + return failure(ArmErrorCode::CommandFailed, "joint velocity or acceleration check failed"); + } + if (!validateSpeedLPredictedJointPositionLimits_(q_measured, qdot, dt)) { + return failure(ArmErrorCode::OutOfJointLimit, "predicted joint position limit exceeded"); + } + if (state_.speedl_line_check_active_) { + const Eigen::VectorXd q_predicted = toEigenVector(q_measured) + qdot * dt; + Eigen::Matrix4d predicted_pose_base; + if (!solver_->fk(toStdVector(q_predicted), predicted_pose_base, true)) { + return failure(ArmErrorCode::CommandFailed, "predicted FK failed"); + } + if (!updateAndValidateSpeedLLineDeviation_(predicted_pose_base.block<3, 1>(0, 3), + is_stop_command, + state_.speedl_command_twist_base_.head<3>(), + target_linear_base)) { + return failure(ArmErrorCode::OutOfWorkspace, "predicted line deviation exceeded"); + } + } + + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = state_.adaptive_stop_reason; + result.joint_velocity.velocity = toStdVector(qdot); + result.twist_base = common::math::vectorToVelocity(state_.speedl_command_twist_base_); + result.settled = is_stop_command && !state_.s_curve_planner_.isMoving(); + if (state_.speedl_capture_pending_) { + auto target_base = target_twist; + if (state_.speedl_frame_ == FrameType::Tool) { + target_base.head<3>() = base_R_tool * target_base.head<3>().eval(); + target_base.tail<3>() = base_R_tool * target_base.tail<3>().eval(); + } + result.reference.valid = true; + result.reference.tcp_pose_base = common::math::matrixToPose(tcp_pose_base); + result.reference.target_base = common::math::vectorToVelocity(target_base); + // The reference and all subsequent steps use this captured Base axis. + state_.speedl_target_ = result.reference.target_base; + state_.speedl_frame_ = FrameType::Base; + state_.speedl_capture_pending_ = false; + } + state_.prev_qdot_command_ = result.joint_velocity.velocity; + return result; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLJointVelocityCommand_( + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& reference, + const double dt) const +{ + const auto& config = speedl_config_.joint_velocity_check(); + if (!config.enable()) { + return true; + } + if (qdot.size() <= 0 || qdot.size() != reference.size() || + dt <= 0.0 || !std::isfinite(dt)) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity check invalid state: qdot_size=" + << qdot.size() << ", reference_size=" << reference.size() + << ", dt=" << dt; + return false; + } + + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + if (!std::isfinite(qdot[i]) || !std::isfinite(reference[i])) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity command non-finite: joint_index=" + << i << ", qdot=" << qdot[i] + << ", reference=" << reference[i]; + return false; + } + } + + const double max_velocity = qdot.cwiseAbs().maxCoeff(); + const double max_acceleration = ((qdot - reference) / dt).cwiseAbs().maxCoeff(); + const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 30.0); + const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 10000.0); + if (max_velocity > velocity_limit || max_acceleration > acceleration_limit) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity command exceeds threshold: max_joint_velocity_rad_s=" + << max_velocity << ", velocity_limit_rad_s=" << velocity_limit + << ", max_joint_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", dt=" << dt; + return false; + } + return true; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLPredictedJointPositionLimits_( + const std::vector& q_measured, + const Eigen::VectorXd& qdot, + const double dt) const +{ + if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { + return true; + } + if (static_cast(q_measured.size()) != qdot.size()) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint position limit check size mismatch: q=" + << q_measured.size() << ", qdot=" << qdot.size(); + return false; + } + + Eigen::VectorXd lower; + Eigen::VectorXd upper; + if (!solver_->getJointPositionLimits(lower, upper) || + lower.size() != qdot.size() || + upper.size() != qdot.size()) { + return true; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + constexpr double kLimitEps = 1e-6; + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + const double q = q_measured[static_cast(i)]; + const double q_next = q + qdot[i] * dt; + const double lo = lower[i]; + const double hi = upper[i]; + if (!std::isfinite(q) || !std::isfinite(q_next) || + !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { + continue; + } + + const bool violates_lower = q_next < lo - kLimitEps; + const bool violates_upper = q_next > hi + kLimitEps; + const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; + const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; + if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] predicted joint position limit exceeded: joint=" + << joint_name << ", q=" << q + << ", q_next=" << q_next + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt; + return false; + } + } + return true; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLCartesianVelocityFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const +{ + const auto& config = speedl_config_.cartesian_velocity_feasibility_check(); + if (!config.enable()) { + return true; + } + + const Eigen::Vector3d desired_linear = desired_twist.head<3>(); + const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); + const double desired_linear_norm = desired_linear.norm(); + const double achieved_linear_norm = achieved_linear.norm(); + const double min_desired_linear_speed = + positiveOr(config.min_desired_linear_speed(), 1e-4); + if (desired_linear_norm >= min_desired_linear_speed) { + const double speed_ratio = achieved_linear_norm / desired_linear_norm; + const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); + const double deviation_deg = + achieved_linear_norm > 1e-9 + ? directionDeviationDeg(desired_linear, achieved_linear) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_linear_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] cartesian velocity infeasible after joint limits " << "limit_candidates=[" + << describeJointLimitCandidates_(q_current, qdot) << "]: desired_linear=[" + << desired_linear.transpose() << "], achieved_linear=[" + << achieved_linear.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + ; + return false; + } + } + + const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); + const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); + const double desired_angular_norm = desired_angular.norm(); + const double achieved_angular_norm = achieved_angular.norm(); + const double min_desired_angular_speed = + positiveOr(config.min_desired_angular_speed(), 1e-4); + if (desired_angular_norm >= min_desired_angular_speed) { + const double speed_ratio = achieved_angular_norm / desired_angular_norm; + const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); + const double deviation_deg = + achieved_angular_norm > 1e-9 + ? directionDeviationDeg(desired_angular, achieved_angular) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_angular_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] cartesian angular velocity infeasible after joint limits: desired_angular=[" + << desired_angular.transpose() << "], achieved_angular=[" + << achieved_angular.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", limit_candidates=[" + << describeJointLimitCandidates_(q_current, qdot) << "]"; + return false; + } + } + + return true; +} + +std::string PinocchioCartesianVelocityPlanner::describeJointLimitCandidates_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const +{ + if (!solver_ || q_current.size() != qdot.size()) { + return "none"; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + + Eigen::VectorXd qd_limits; + const bool has_qd_limits = + solver_->getJointVelocityLimits(qd_limits) && qd_limits.size() == qdot.size(); + Eigen::VectorXd lower; + Eigen::VectorXd upper; + const bool has_q_limits = + solver_->getJointPositionLimits(lower, upper) && + lower.size() == q_current.size() && + upper.size() == q_current.size(); + + std::vector candidates; + constexpr double kVelocityRatio = 0.98; + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + + std::vector reasons; + if (has_qd_limits) { + const double qd_limit = std::abs(qd_limits[i]); + if (std::isfinite(qd_limit) && qd_limit > 0.0 && + std::abs(qdot[i]) >= kVelocityRatio * qd_limit) { + std::ostringstream oss; + oss << "qd=" << qdot[i] << "/" << qd_limit; + reasons.push_back(oss.str()); + } + } + + if (has_q_limits) { + const double q = q_current[i]; + const double lo = lower[i]; + const double hi = upper[i]; + if (std::isfinite(q) && std::isfinite(lo) && std::isfinite(hi) && hi > lo) { + const double margin = std::max(0.02, 0.02 * (hi - lo)); + if (q <= lo + margin) { + std::ostringstream oss; + oss << "near_lower q=" << q << "/" << lo; + reasons.push_back(oss.str()); + } + if (q >= hi - margin) { + std::ostringstream oss; + oss << "near_upper q=" << q << "/" << hi; + reasons.push_back(oss.str()); + } + } + } + + if (!reasons.empty()) { + std::ostringstream item; + item << joint_name << "("; + for (std::size_t j = 0; j < reasons.size(); ++j) { + if (j > 0) { + item << "; "; + } + item << reasons[j]; + } + item << ")"; + candidates.push_back(item.str()); + } + } + + if (candidates.empty()) { + return "none"; + } + std::ostringstream oss; + for (std::size_t i = 0; i < candidates.size(); ++i) { + if (i > 0) { + oss << ", "; + } + oss << candidates[i]; + } + return oss.str(); +} + +bool PinocchioCartesianVelocityPlanner::updateSpeedLLimits_(const SpeedLOptions& options) +{ + const double jerk_max = positiveOr(speedl_config_.linear_jerk_max(), 10.0); + const double requested_jerk = options.linear_jerk.value_or(jerk_max); + // Validate before clamping: invalid requests must not become valid limits. + if (!speedl_configured_ || !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(requested_jerk) || requested_jerk <= 0.0) { + return false; + } + const double acceleration = std::min(options.acceleration, + positiveOr(speedl_config_.linear_acceleration_max(), 5.0)); + const double angular_acceleration = std::min(options.acceleration, + positiveOr(speedl_config_.angular_acceleration_max(), 5.0)); + const double jerk = std::min(requested_jerk, jerk_max); + const bool continuous = options.continuous_linear_reversal.value_or( + !speedl_config_.has_continuous_linear_reversal() || speedl_config_.continuous_linear_reversal()); + if (std::abs(state_.speedl_applied_acceleration_ - acceleration) <= 1e-9 && + std::abs(state_.speedl_applied_angular_acceleration_ - angular_acceleration) <= 1e-9 && + std::abs(state_.speedl_applied_linear_jerk_ - jerk) <= 1e-9) { + state_.s_curve_planner_.setContinuousLinearReversal(continuous); + return true; + } + + // Commit both sets of limits and the policy together. A rejected update + // must leave the previous command and its entire future profile intact. + auto candidate = state_.s_curve_planner_; + candidate.setLinearConstraints( + positiveOr(speedl_config_.linear_velocity_max(), .55), + acceleration, jerk); + candidate.setAngularConstraints( + positiveOr(speedl_config_.angular_velocity_max(), 1.0), + angular_acceleration, positiveOr(speedl_config_.angular_jerk_max(), 12.0)); + candidate.setContinuousLinearReversal(continuous); + state_.s_curve_planner_ = std::move(candidate); + state_.speedl_applied_acceleration_ = acceleration; + state_.speedl_applied_angular_acceleration_ = angular_acceleration; + state_.speedl_applied_linear_jerk_ = jerk; + return true; +} + +Result PinocchioCartesianVelocityPlanner::submit( + const CartesianVelocity& target, const SpeedLOptions& options, const FrameType frame) +{ + pending_.reset(); + if (!speedl_configured_) { + return Result::failure(ArmErrorCode::RobotNotReady, "velocity planner is not configured"); + } + if (!state_.adaptive_stop_reason.ok()) { + return Result::failure(ArmErrorCode::RobotNotReady, + "adaptive speed stop is in progress; reset before submitting another command"); + } + if ((frame != FrameType::Base && frame != FrameType::Tool) || + !std::isfinite(common::math::velocityToVector(target).norm())) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid velocity target or frame"); + } + try { + if (!updateSpeedLLimits_(options)) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid velocity planning limits"); + } + } catch (const std::invalid_argument& error) { + return Result::failure(ArmErrorCode::InvalidArgument, error.what()); + } catch (const std::runtime_error& error) { + return Result::failure(ArmErrorCode::CommandFailed, error.what()); + } + state_.speedl_target_ = target; + state_.speedl_frame_ = frame; + state_.speedl_capture_pending_ = options.capture_reference; + state_.speedl_command_ready_ = true; + return Result::success(); +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp new file mode 100644 index 00000000..20600678 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp @@ -0,0 +1,1161 @@ +#include + +#include +#include +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" +#include "common/io/proto_file_io.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { +namespace { +constexpr double kDt = .001; +using Twist = Eigen::Matrix; + +// A successful planner candidate becomes the executed state only after the +// controller accepts it. These pure planner tests model successful submission. +CartesianVelocityStep stepAndCommit(PinocchioCartesianVelocityPlanner& planner, + double dt, const std::vector& q, + const std::vector& qd, double scaling = 1) +{ + auto result = planner.step(dt, q, qd, scaling); + if (result.status.ok()) planner.commitStep(); + return result; +} + +// Exercise the production planner and real URDF kinematics, without motor I/O. +class PinocchioSpeedLLimits : public ::testing::Test { +protected: + void SetUp() override { + const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + auto ik = arms.arm().robot_arms(0).kinematics().pinocchio_dls_ik_solver(); + ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string()); + solver_ = std::make_shared(ik); + ASSERT_TRUE(solver_->init()); + planner_ = std::make_unique(solver_); + limits_.set_linear_velocity_max(.2); + limits_.set_linear_acceleration_max(.4); + limits_.set_linear_jerk_max(2); + limits_.set_angular_velocity_max(1); + limits_.set_angular_acceleration_max(.8); + limits_.set_angular_jerk_max(4); + limits_.set_enforce_joint_acceleration_limits(false); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + } + + struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; }; + Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options, + bool angular = false, int steps = 2200) { + Peaks peaks; + const auto submitted = planner_->submit(target, options, FrameType::Base); + if (!submitted.ok()) { + ADD_FAILURE() << submitted.message; + return peaks; + } + Twist previous = last_twist_; + Twist previous_acceleration = Twist::Zero(); + for (int i = 0; i < steps; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + if (!result.status.ok()) { + ADD_FAILURE() << "Planning failed at sample " << i << ": " << result.status.message; + break; + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + const int offset = angular ? 3 : 0; + peaks.velocity = std::max(peaks.velocity, velocity.segment<3>(offset).norm()); + peaks.acceleration = std::max(peaks.acceleration, acceleration.segment<3>(offset).norm()); + peaks.jerk = std::max(peaks.jerk, jerk.segment<3>(offset).norm()); + previous = velocity; + previous_acceleration = acceleration; + last_twist_ = velocity; + } + return peaks; + } + + void expectPeaks(const Peaks& p, double velocity, double acceleration, double jerk) { + // These trajectories contain plateaus: limits must be reached, as well + // as obeyed, so an unintended smaller cap cannot pass the test. + EXPECT_NEAR(p.velocity, velocity, 1e-8); + EXPECT_NEAR(p.acceleration, acceleration, 1e-8); + EXPECT_NEAR(p.jerk, jerk, 1e-6); + } + + std::shared_ptr solver_; + std::unique_ptr planner_; + config::SpeedLPlannerConfig limits_; + const std::vector q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + const std::vector qd_ = std::vector(7, 0); + Twist last_twist_{Twist::Zero()}; +}; + +TEST_F(PinocchioSpeedLLimits, ExcessiveRequestsRespectAllLinearLimits) { + SpeedLOptions options; + options.acceleration = 60; + options.linear_jerk = 60; + CartesianVelocity target; + target.vx = .6; + target.vy = .8; + expectPeaks(sample(target, options), .2, .4, 2); +} + +TEST_F(PinocchioSpeedLLimits, LowerRequestsRemainEffective) { + SpeedLOptions options; + options.acceleration = .15; + options.linear_jerk = .8; + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options), .2, .15, .8); +} + +TEST_F(PinocchioSpeedLLimits, OmittedJerkRestoresArmLimit) { + SpeedLOptions options; + options.acceleration = .4; + options.linear_jerk = .3; + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + options.linear_jerk.reset(); + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options), .2, .4, 2); +} + +TEST_F(PinocchioSpeedLLimits, AccelerationOnlyRequestsAndStopAreCapped) { + SpeedLOptions options; + options.acceleration = 60; + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options, false, 1200), .2, .4, 2); + const auto stop = sample({}, options, false, 1200); + EXPECT_LE(stop.velocity, .2); + EXPECT_NEAR(stop.acceleration, .4, 1e-8); + EXPECT_NEAR(stop.jerk, 2, 1e-6); + EXPECT_NEAR(last_twist_[1], 0, 1e-12); +} + +TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) { + limits_.set_linear_acceleration_max(.2); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = .3; + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + // Linear effective acceleration stays at .2, but angular must change. + options.acceleration = .6; + CartesianVelocity target; + target.wy = 2; + expectPeaks(sample(target, options, true), 1, .6, 4); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + options.acceleration = 60; + expectPeaks(sample(target, options, true), 1, .8, 4); +} + +TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) { + for (double invalid : {0.0, -1.0, 1e-12, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SpeedLOptions options; + options.acceleration = invalid; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + options.acceleration = .3; + options.linear_jerk = invalid; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + } +} + +TEST_F(PinocchioSpeedLLimits, IncompatibleLimitsRejectStopWithoutChangingPreviousCommand) { + limits_.set_linear_velocity_max(1); + limits_.set_linear_acceleration_max(3); + limits_.set_linear_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + CartesianVelocity target; + target.vy = .8; + SpeedLOptions options; + options.acceleration = 3; + options.linear_jerk = 10; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + + // Current a=1: lowering a to .1 would jump; jerk=.01 cannot remove + // acceleration before exceeding the velocity bound. Both must reject. + for (bool lower_jerk : {false, true}) { + auto candidate = *planner_; + auto reference = *planner_; + auto invalid_options = options; + if (lower_jerk) invalid_options.linear_jerk = .01; + else invalid_options.acceleration = .1; + const auto rejected = candidate.submit({}, invalid_options, FrameType::Base); + EXPECT_FALSE(rejected.ok()); + EXPECT_FALSE(rejected.message.empty()); + for (int i = 0; i < 100; ++i) { + const auto actual = stepAndCommit(candidate, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + // The rejected request must not poison a subsequent stop at valid limits. + ASSERT_TRUE(candidate.submit({}, options, FrameType::Base).ok()); + CartesianVelocityStep stopped; + for (int i = 0; i < 1200; ++i) { + stopped = stepAndCommit(candidate, kDt, q_, qd_); + ASSERT_TRUE(stopped.status.ok()) << stopped.status.message; + } + EXPECT_NEAR(common::math::velocityToVector(stopped.twist_base).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, RejectedAngularLimitDoesNotPartiallyApplyLinearLimitOrPolicy) { + limits_.set_linear_acceleration_max(3); + limits_.set_angular_acceleration_max(3); + limits_.set_angular_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + CartesianVelocity target; + target.vy = .1; + target.wy = .8; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + options.acceleration = .5; // Linear a=.2 fits; angular a=1 does not. + options.continuous_linear_reversal = false; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + for (int i = 0; i < 200; ++i) { + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } +} + +TEST_F(PinocchioSpeedLLimits, InvalidConfigurationKeepsPreviousCommand) { + CartesianVelocity target; + target.vy = .1; + SpeedLOptions options; + options.acceleration = .3; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + using Config = config::SpeedLPlannerConfig; + for (auto setter : {&Config::set_linear_velocity_max, &Config::set_linear_acceleration_max, + &Config::set_linear_jerk_max, &Config::set_angular_velocity_max, + &Config::set_angular_acceleration_max, &Config::set_angular_jerk_max, + &Config::set_linear_target_replan_threshold, + &Config::set_angular_target_replan_threshold}) { + for (double invalid : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + (invalid_config.*setter)(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(actual.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } + } + for (double invalid : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + invalid_config.mutable_adaptive_speed()->set_enable(true); + invalid_config.mutable_adaptive_speed()->set_lookahead_s(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + for (double invalid : {-1.0, 1.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + invalid_config.mutable_adaptive_speed()->set_enable(true); + invalid_config.mutable_adaptive_speed()->set_min_speed_ratio(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + // Unspecified protobuf scalars remain zero and select the existing defaults. + EXPECT_TRUE(planner_->configureSpeedL(Config{}, q_.size())); +} + +TEST_F(PinocchioSpeedLLimits, StreamingNearZeroMotionKeepsProfileAndAcceleration) { + SpeedLOptions options; + options.acceleration = .3; + options.linear_jerk = .01; + options.continuous_linear_reversal = false; + CartesianVelocity target; + target.vy = .02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 1; i <= 200; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + const double time = i * kDt; + EXPECT_NEAR(result.twist_base.vy, .5 * *options.linear_jerk * time * time, 1e-12); + } + + // Change axis below the former reset threshold while acceleration is + // nonzero. The transition must preserve it, rather than restart from rest. + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto first = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_GT(first.twist_base.vy, 0); + ASSERT_LT(first.twist_base.vy, 1e-6); + target.vy = 0; + target.vx = .02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto switching = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(switching.status.ok()) << switching.status.message; + EXPECT_GT(switching.twist_base.vy, first.twist_base.vy); + const Twist first_v = common::math::velocityToVector(first.twist_base); + const Twist next_v = common::math::velocityToVector(switching.twist_base); + EXPECT_LE(((next_v - 2 * first_v) / (kDt * kDt)).head<3>().norm(), + *options.linear_jerk + 1e-7); +} + +TEST_F(PinocchioSpeedLLimits, StreamingDirectionChangesRespectAccelerationAndJerk) { + for (const double jerk : {10.0, 30.0}) { + SCOPED_TRACE(jerk); + limits_.set_continuous_linear_reversal(true); + limits_.set_linear_acceleration_max(5); + limits_.set_linear_jerk_max(jerk); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = .5; + CartesianVelocity target; + target.vy = .02; + sample(target, options, false, 300); + ASSERT_NEAR(last_twist_[1], .02, 1e-10); + + // Same acceleration/jerk: the policy override must bypass their cache. + options.continuous_linear_reversal = false; + double min_speed = .02; + double max_error = 0; + Twist previous = last_twist_; + Twist previous_acceleration = Twist::Zero(); + for (int i = 0; i < 2000; ++i) { + const double angle = (i / 20) * .01; + target.vx = .02 * std::sin(angle); + target.vy = .02 * std::cos(angle); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + const Twist actual = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (actual - previous) / kDt; + const Twist discrete_jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(acceleration.head<3>().norm(), options.acceleration + 1e-7); + EXPECT_LE(discrete_jerk.head<3>().norm(), jerk + 1e-5); + previous = actual; + previous_acceleration = acceleration; + last_twist_ = actual; + min_speed = std::min(min_speed, actual.head<3>().norm()); + max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm()); + } + EXPECT_GT(min_speed, .019); // Smooth tracking may lag; it must not stop periodically. + EXPECT_LT(max_error, .002); + // Once the target stops changing, converge to its exact direction. + sample(target, options, false, 300); + EXPECT_NEAR((last_twist_ - common::math::velocityToVector(target)).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, ContactReversalStillCrossesZeroAfterStreamingAlignment) { + limits_.set_linear_acceleration_max(1); + limits_.set_linear_jerk_max(4); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = 1; + options.continuous_linear_reversal = false; + CartesianVelocity target; + target.vy = .02; + sample(target, options, false, 300); + ASSERT_NEAR(last_twist_[1], .02, 1e-10); + + options.continuous_linear_reversal = true; + target.vy = -.02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + last_twist_ = common::math::velocityToVector(result.twist_base); + } + EXPECT_NEAR(last_twist_[1], 0, 1e-10); + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_LT(result.twist_base.vy, -.0003); +} +TEST_F(PinocchioSpeedLLimits, StepRequiresCommandAndNeverReturnsOldOutputOnFailure) { + auto expect_empty_failure = [](const CartesianVelocityStep& result) { + EXPECT_FALSE(result.status.ok()); + EXPECT_FALSE(result.status.message.empty()); + EXPECT_TRUE(result.joint_velocity.velocity.empty()); + EXPECT_DOUBLE_EQ(common::math::velocityToVector(result.twist_base).norm(), 0); + EXPECT_FALSE(result.reference.valid); + }; + const auto unsubmitted = stepAndCommit(*planner_, kDt, q_, qd_); + EXPECT_EQ(unsubmitted.status.code, ArmErrorCode::RobotNotReady); + expect_empty_failure(unsubmitted); + + CartesianVelocity target; + target.vy = .02; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto valid = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(valid.status.ok()) << valid.status.message; + ASSERT_EQ(valid.joint_velocity.velocity.size(), q_.size()); + ASSERT_GT(valid.twist_base.vy, 0); + ASSERT_TRUE(valid.reference.valid); + for (double dt : {0.0, -kDt, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(dt); + expect_empty_failure(stepAndCommit(*planner_, dt, q_, qd_)); + } + expect_empty_failure(stepAndCommit(*planner_, kDt, {}, qd_)); + expect_empty_failure(stepAndCommit(*planner_, kDt, q_, {})); +} + +TEST_F(PinocchioSpeedLLimits, OnlyCommittedSuccessfulStepsAdvanceProfileAndReference) { + CartesianVelocity target; + target.vy = .1; + SpeedLOptions options; + options.acceleration = .4; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + const auto first = planner_->step(kDt, q_, qd_); + const auto uncommitted = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_TRUE(uncommitted.status.ok()) << uncommitted.status.message; + EXPECT_EQ(first.joint_velocity.velocity, uncommitted.joint_velocity.velocity); + EXPECT_TRUE(first.reference.valid); + EXPECT_TRUE(uncommitted.reference.valid); + planner_->commitStep(); + + const auto second = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(second.status.ok()) << second.status.message; + EXPECT_FALSE(second.reference.valid); + EXPECT_GT(common::math::velocityToVector(second.twist_base).norm(), + common::math::velocityToVector(first.twist_base).norm()); + // An invalid request must discard the pending second command. In + // particular, accidentally committing after failure cannot advance it. + EXPECT_FALSE(planner_->step(0, q_, qd_).status.ok()); + planner_->commitStep(); + const auto retried = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(retried.status.ok()) << retried.status.message; + EXPECT_EQ(retried.joint_velocity.velocity, second.joint_velocity.velocity); +} + +TEST_F(PinocchioSpeedLLimits, ToolReferenceUsesFirstStepPoseAndKeepsBaseDirection) { + CartesianVelocity target; + target.vx = .03; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + auto first_q = q_; + first_q[0] += .1; + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(first_q, pose, true)); + const Eigen::Vector3d expected_base = pose.block<3, 3>(0, 0) * Eigen::Vector3d(.03, 0, 0); + const auto first = stepAndCommit(*planner_, kDt, first_q, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_TRUE(first.reference.valid); + EXPECT_NEAR(first.reference.tcp_pose_base.x, pose(0, 3), 1e-12); + EXPECT_NEAR(first.reference.tcp_pose_base.y, pose(1, 3), 1e-12); + EXPECT_NEAR(first.reference.tcp_pose_base.z, pose(2, 3), 1e-12); + EXPECT_NEAR((common::math::velocityToVector(first.reference.target_base).head<3>() - expected_base).norm(), + 0, 1e-12); + PinocchioCartesianVelocityPlanner base_planner(solver_); + ASSERT_TRUE(base_planner.configureSpeedL(limits_, q_.size())); + options.capture_reference = false; + ASSERT_TRUE(base_planner.submit(first.reference.target_base, options, FrameType::Base).ok()); + ASSERT_TRUE(stepAndCommit(base_planner, kDt, first_q, qd_).status.ok()); + auto later_q = first_q; + later_q[0] += .2; + Eigen::Matrix4d later_pose; + ASSERT_TRUE(solver_->fk(later_q, later_pose, true)); + // Ensure the changed pose would produce a different Base direction if + // Tool conversion were incorrectly repeated after capturing the reference. + EXPECT_GT((later_pose.block<3, 3>(0, 0) * Eigen::Vector3d(.03, 0, 0) - expected_base).norm(), 1e-5); + // Compare long enough that the limiter's own transient axis lock cannot + // hide accidental Tool-frame reconversion on later control cycles. + for (int i = 0; i < 300; ++i) { + const auto later = stepAndCommit(*planner_, kDt, later_q, qd_); + const auto base = stepAndCommit(base_planner, kDt, later_q, qd_); + ASSERT_TRUE(later.status.ok()) << later.status.message; + ASSERT_TRUE(base.status.ok()) << base.status.message; + EXPECT_FALSE(later.reference.valid); + EXPECT_NEAR((common::math::velocityToVector(later.twist_base) - + common::math::velocityToVector(base.twist_base)).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, StopSettlesProfileBeforeRestartingOnAnotherAxis) { + limits_.set_linear_acceleration_max(.5); + limits_.set_linear_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + CartesianVelocity target; + target.vx = .05; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 800; ++i) { + const auto step = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(step.status.ok()) << step.status.message; + EXPECT_FALSE(step.settled); + } + + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + bool small_command_before_settled = false; + CartesianVelocityStep stopped; + for (int i = 0; i < 500; ++i) { + stopped = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(stopped.status.ok()) << stopped.status.message; + double squared_speed = 0; + for (double velocity : stopped.joint_velocity.velocity) squared_speed += velocity * velocity; + if (std::sqrt(squared_speed) < 1e-3 && !stopped.settled) { + small_command_before_settled = true; + } + if (stopped.settled) break; + } + EXPECT_TRUE(small_command_before_settled); + ASSERT_TRUE(stopped.settled); + EXPECT_DOUBLE_EQ(common::math::velocityToVector(stopped.twist_base).norm(), 0); + + PinocchioCartesianVelocityPlanner fresh(solver_); + ASSERT_TRUE(fresh.configureSpeedL(limits_, q_.size())); + target.vx = 0; + target.vy = .05; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(fresh.submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 300; ++i) { + const auto restarted = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(fresh, kDt, q_, qd_); + ASSERT_TRUE(restarted.status.ok()) << restarted.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(restarted.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(restarted.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } +} + +TEST_F(PinocchioSpeedLLimits, ContinuousTurnFinishesLineAlignmentWithoutDisablingDriftCheck) { + limits_.set_linear_acceleration_max(.5); + limits_.set_linear_jerk_max(10); + auto* line = limits_.mutable_line_deviation_check(); + line->set_enable(true); + line->set_line_deviation_stop_m(.005); + line->set_line_direction_reset_deg(10); + line->set_line_check_min_distance_m(.01); + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + options.continuous_linear_reversal = true; + + for (FrameType frame : {FrameType::Base, FrameType::Tool}) { + SCOPED_TRACE(static_cast(frame)); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + auto q = q_; + auto qd = qd_; + // Follow real velocity IK with FK feedback, including the curved + // transition from +X to +Y. Resubmission must not erase the reference. + for (int i = 0; i < 2600; ++i) { + Twist target = Twist::Zero(); + target[i < 800 ? 0 : 1] = .05; + if (frame == FrameType::Tool) { + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(q, pose, true)); + target.head<3>() = pose.block<3, 3>(0, 0).transpose() * target.head<3>().eval(); + } + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, frame).ok()); + const auto step = stepAndCommit(*planner_, kDt, q, qd); + ASSERT_TRUE(step.status.ok()) << "sample=" << i << ": " << step.status.message; + qd = step.joint_velocity.velocity; + for (std::size_t joint = 0; joint < q.size(); ++joint) q[joint] += qd[joint] * kDt; + } + + // Introduce a measured 8 mm cross-track disturbance after steady +Y + // travel. The unchanged Base target must still trigger the 5 mm guard. + Eigen::Matrix4d before; + ASSERT_TRUE(solver_->fk(q, before, true)); + auto disturbed_pose = before; + disturbed_pose(0, 3) += .008; + solver_->update_joints_state(q); + ASSERT_TRUE(solver_->ik(disturbed_pose, q, true)); + Eigen::Matrix4d measured; + ASSERT_TRUE(solver_->fk(q, measured, true)); + ASSERT_GT(measured(0, 3) - before(0, 3), .007); + Twist target = Twist::Zero(); + target[1] = .05; + if (frame == FrameType::Tool) { + target.head<3>() = measured.block<3, 3>(0, 0).transpose() * target.head<3>().eval(); + } + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, frame).ok()); + const auto rejected = stepAndCommit(*planner_, kDt, q, qd); + EXPECT_EQ(rejected.status.code, ArmErrorCode::OutOfWorkspace) << rejected.status.message; + EXPECT_TRUE(rejected.joint_velocity.velocity.empty()); + } +} + +TEST_F(PinocchioSpeedLLimits, ResetDiscardsInterruptedProfileAndRequiresNewCommand) { + CartesianVelocity target; + target.vy = .15; + SpeedLOptions options; + options.acceleration = .4; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + // Simulate an external hard stop while the S-curve still has acceleration. + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + EXPECT_EQ(stepAndCommit(*planner_, kDt, q_, qd_).status.code, ArmErrorCode::RobotNotReady); + + PinocchioCartesianVelocityPlanner fresh(solver_); + ASSERT_TRUE(fresh.configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(fresh.reset(q_, qd_).ok()); + target.vy = 0; + target.vx = .1; + options.capture_reference = false; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(fresh.submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 300; ++i) { + const auto restarted = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(fresh, kDt, q_, qd_); + ASSERT_TRUE(restarted.status.ok()) << restarted.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_FALSE(restarted.reference.valid); + EXPECT_EQ(restarted.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(restarted.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } +} + +TEST_F(PinocchioSpeedLLimits, ResetUsesMeasuredTwistAndJointVelocity) { + limits_.set_enforce_joint_acceleration_limits(true); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + auto measured_qd = qd_; + measured_qd[0] = .05; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver_->computePoseAndJacobianBaseAtQ(q_, true, pose, jacobian, rotation)); + const Twist measured_twist = jacobian * Eigen::Map(measured_qd.data(), measured_qd.size()); + ASSERT_TRUE(planner_->reset(q_, measured_qd).ok()); + SpeedLOptions options; + options.acceleration = .4; + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(measured_twist), options, + FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, q_, measured_qd); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_NEAR((common::math::velocityToVector(result.twist_base) - measured_twist).norm(), 0, 1e-12); + // A zero reset baseline would clip this below .01 rad/s on the first cycle. + EXPECT_GT(result.joint_velocity.velocity[0], .03); +} + +TEST_F(PinocchioSpeedLLimits, ScalingPreservesBoundsAndCapturedToolReferenceThroughPause) { + SpeedLOptions options; + options.acceleration = .8; + options.capture_reference = true; + CartesianVelocity target; + target.vx = 1; // Clamp to the arm limits before applying the speed ratio. + target.wy = 2; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(q_, pose, true)); + Twist capped_base = Twist::Zero(); + capped_base.head<3>() = pose.block<3, 3>(0, 0) * Eigen::Vector3d(.2, 0, 0); + capped_base.tail<3>() = pose.block<3, 3>(0, 0) * Eigen::Vector3d(0, 1, 0); + auto later_q = q_; + later_q[0] += .2; + Twist previous = Twist::Zero(); + Twist previous_acceleration = Twist::Zero(); + int captures = 0; + int samples = 0; + for (double scaling : {1.0, .5, 0.0, 1.0}) { + SCOPED_TRACE(scaling); + CartesianVelocityStep result; + for (int i = 0; i < 2200; ++i, ++samples) { + result = stepAndCommit(*planner_, kDt, samples == 0 ? q_ : later_q, qd_, scaling); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_FALSE(result.settled); // Pausing must retain the active request. + if (result.reference.valid) { + ++captures; + EXPECT_NEAR(common::math::velocityToVector(result.reference.target_base).head<3>().norm(), 1, 1e-12); + EXPECT_NEAR(common::math::velocityToVector(result.reference.target_base).tail<3>().norm(), 2, 1e-12); + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(velocity.head<3>().norm(), .2 + 1e-10); + EXPECT_LE(velocity.tail<3>().norm(), 1 + 1e-10); + EXPECT_LE(acceleration.head<3>().norm(), .4 + 1e-8); + EXPECT_LE(acceleration.tail<3>().norm(), .8 + 1e-8); + EXPECT_LE(jerk.head<3>().norm(), 2 + 1e-6); + EXPECT_LE(jerk.tail<3>().norm(), 4 + 1e-6); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_NEAR((previous - scaling * capped_base).norm(), 0, 1e-10); + if (scaling == 0) { + for (double qdot : result.joint_velocity.velocity) EXPECT_DOUBLE_EQ(qdot, 0); + } + } + EXPECT_EQ(captures, 1); +} + +TEST_F(PinocchioSpeedLLimits, InvalidScalingOrResetLeavesActiveProfileUnchanged) { + SpeedLOptions options; + options.acceleration = .4; + CartesianVelocity target; + target.vy = .1; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + for (double invalid : {-1.0, 1.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + const auto rejected = stepAndCommit(*planner_, kDt, q_, qd_, invalid); + EXPECT_EQ(rejected.status.code, ArmErrorCode::InvalidArgument); + EXPECT_TRUE(rejected.joint_velocity.velocity.empty()); + } + EXPECT_EQ(planner_->reset({}, qd_).code, ArmErrorCode::InvalidDof); + auto invalid_qd = qd_; + invalid_qd[0] = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(planner_->reset(q_, invalid_qd).code, ArmErrorCode::InvalidArgument); + for (int i = 0; i < 300; ++i) { + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } +} + +TEST_F(PinocchioSpeedLLimits, StoppedOrPausedProfileCannotGenerateNullspaceMotion) { + auto policy = solver_->jointLimitPolicy(); + policy.mutable_avoidance()->set_enable(true); + solver_->setJointLimitPolicy(policy); + auto near_limit = q_; + near_limit[6] = 1.5; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver_->computePoseAndJacobianBaseAtQ(near_limit, true, pose, jacobian, rotation)); + std::vector nullspace_velocity; + ASSERT_TRUE(solver_->solveVelocityBase(jacobian, Twist::Zero(), near_limit, nullspace_velocity, + std::numeric_limits::infinity())); + EXPECT_GT(Eigen::Map(nullspace_velocity.data(), nullspace_velocity.size()).norm(), 1e-6); + ASSERT_TRUE(planner_->reset(near_limit, qd_).ok()); + SpeedLOptions options; + options.acceleration = .4; + CartesianVelocity target; + target.vy = .1; + for (bool pause : {false, true}) { + ASSERT_TRUE(planner_->submit(pause ? target : CartesianVelocity{}, options, FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, near_limit, qd_, pause ? 0 : 1); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_EQ(result.settled, !pause); + for (double qdot : result.joint_velocity.velocity) EXPECT_DOUBLE_EQ(qdot, 0); + } +} + +class PinocchioQpSpeedLIntegration : public ::testing::Test { +protected: + void SetUp() override { + const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + const auto& arm = arms.arm().robot_arms(0); + auto ik = arm.kinematics().pinocchio_qp_ik_solver(); + ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string()); + solver_ = std::make_shared(ik); + ASSERT_TRUE(solver_->init()); + planner_ = std::make_unique(solver_); + limits_ = arm.motion().speed_l().pinocchio_cartesian_motion_planner(); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(solver_->getJointPositionLimits(lower_, upper_)); + ASSERT_TRUE(solver_->getJointVelocityLimits(velocity_limits_)); + std::vector names; + ASSERT_TRUE(solver_->getChainJointNames(names)); + acceleration_limits_.assign(names.size(), 0); + for (std::size_t i = 0; i < names.size(); ++i) { + for (const auto& limit : ik.joint_limit_policy().limits().joints()) { + if (limit.joint_name() == names[i]) acceleration_limits_[i] = limit.qdd(); + } + ASSERT_GT(acceleration_limits_[i], 0); + } + } + + // Integrate the actual joint command, not the requested Cartesian twist. + ::testing::AssertionResult advance(CartesianVelocityStep& result, double scaling = 1) { + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver_->computePoseAndJacobianBaseAtQ(q_, true, pose, jacobian, rotation)) + return ::testing::AssertionFailure() << "FK/Jacobian failed"; + result = stepAndCommit(*planner_, kDt, q_, qd_, scaling); + if (!result.status.ok()) return ::testing::AssertionFailure() << result.status.message; + if (result.joint_velocity.velocity.size() != q_.size()) + return ::testing::AssertionFailure() << "wrong command size"; + const auto& next_qd = result.joint_velocity.velocity; + const Eigen::Map velocity(next_qd.data(), next_qd.size()); + const Twist desired = common::math::velocityToVector(result.twist_base); + if (!velocity.allFinite() || !desired.allFinite()) + return ::testing::AssertionFailure() << "non-finite command"; + const double residual = (jacobian * velocity - desired).norm(); + if (residual > 1e-5) + return ::testing::AssertionFailure() << "Cartesian equality residual=" << residual; + for (std::size_t i = 0; i < q_.size(); ++i) { + const double next_q = q_[i] + next_qd[i] * kDt; + const double acceleration = std::abs(next_qd[i] - qd_[i]) / kDt; + if (next_q < lower_[i] - 1e-7 || next_q > upper_[i] + 1e-7 || + std::abs(next_qd[i]) > velocity_limits_[i] + 1e-6 || + acceleration > acceleration_limits_[i] + 1e-3) { + return ::testing::AssertionFailure() << "joint=" << i << " q=" << next_q + << " qd=" << next_qd[i] << " qdd=" << acceleration; + } + } + qd_ = next_qd; + for (std::size_t i = 0; i < q_.size(); ++i) q_[i] += qd_[i] * kDt; + return ::testing::AssertionSuccess(); + } + + std::shared_ptr solver_; + std::unique_ptr planner_; + config::SpeedLPlannerConfig limits_; + std::vector q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + std::vector qd_ = std::vector(7, 0); + std::vector acceleration_limits_; + Eigen::VectorXd lower_, upper_, velocity_limits_; +}; + +TEST_F(PinocchioQpSpeedLIntegration, TouchingAtShoulderLimitKeepsStraightToolMotion) { + // Recorded off-centre touch pose that previously accumulated 5 mm drift. + q_ = {.2667416268, 1.57, .9599837007, 1.223555827, + -2.912197805, -.4882931474, -.03457454408}; + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + Eigen::Matrix4d initial_pose; + ASSERT_TRUE(solver_->fk(q_, initial_pose, true)); + const Eigen::Vector3d axis = -initial_pose.block<3, 3>(0, 0).col(1); + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + double max_lateral_error = 0; + Eigen::Matrix4d pose; + CartesianVelocityStep result; + for (int i = 0; i < 2000; ++i) { + ASSERT_TRUE(advance(result)) << "sample=" << i; + ASSERT_TRUE(solver_->fk(q_, pose, true)); + const Eigen::Vector3d delta = pose.block<3, 1>(0, 3) - initial_pose.block<3, 1>(0, 3); + max_lateral_error = std::max(max_lateral_error, (delta - axis * axis.dot(delta)).norm()); + } + const Eigen::Vector3d delta = pose.block<3, 1>(0, 3) - initial_pose.block<3, 1>(0, 3); + EXPECT_GT(axis.dot(delta), .06); // A stopped or heavily slowed arm must not pass. + EXPECT_LT(axis.dot(delta), .081); + EXPECT_LT(max_lateral_error, .0002); + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), .04, 1e-7); +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveSpeedSlowsTouchTargetThroughSCurveBeforeWristLimit) { + const std::vector initial{.250503734519, 1.1370261797, 1.58375920865, + .774603121123, -2.87240757376, .387646573327, -.395308298864}; + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + for (bool adaptive : {false, true}) { + SCOPED_TRACE(adaptive); + limits_.mutable_adaptive_speed()->set_enable(adaptive); + limits_.mutable_adaptive_speed()->set_lookahead_s(.15); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(0); // Legacy near-zero hold. + ASSERT_TRUE(planner_->configureSpeedL(limits_, initial.size())); + q_ = initial; + qd_.assign(initial.size(), 0); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Twist previous = Twist::Zero(), previous_acceleration = Twist::Zero(); + double max_speed = 0, max_acceleration = 0, max_jerk = 0, late_max_speed = 0; + int failure_tick = -1; + for (int tick = 0; tick < (adaptive ? 6000 : 3000); ++tick) { + CartesianVelocityStep result; + const auto advanced = advance(result); + if (!advanced) { + failure_tick = tick; + if (adaptive) ADD_FAILURE() << "tick=" << tick << ": " << advanced.message(); + break; + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + max_speed = std::max(max_speed, velocity.head<3>().norm()); + max_acceleration = std::max(max_acceleration, acceleration.head<3>().norm()); + max_jerk = std::max(max_jerk, jerk.head<3>().norm()); + if (tick >= 5000) late_max_speed = std::max(late_max_speed, velocity.head<3>().norm()); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_LE(max_speed, .04 + 1e-8); + EXPECT_LE(max_acceleration, options.acceleration + 1e-5); + EXPECT_LE(max_jerk, *options.linear_jerk + 1e-3); + EXPECT_GT(max_speed, .039); + if (adaptive) { + EXPECT_EQ(failure_tick, -1); + EXPECT_LT(previous.head<3>().norm(), .035); + RecordProperty("adaptive_final_speed_m_s", std::to_string(previous.head<3>().norm())); + RecordProperty("adaptive_max_acceleration_m_s2", std::to_string(max_acceleration)); + RecordProperty("adaptive_max_jerk_m_s3", std::to_string(max_jerk)); + RecordProperty("adaptive_wrist_position_rad", std::to_string(q_[6])); + EXPECT_LT(late_max_speed, 1e-5); // No spurious speed recovery near rest. + RecordProperty("near_rest_max_speed_m_s", std::to_string(late_max_speed)); + if (failure_tick < 0) { + const double wrist_before_reverse = q_[6]; + CartesianVelocity retreat; + retreat.vy = .04; + ASSERT_TRUE(planner_->submit(retreat, options, FrameType::Tool).ok()); + for (int tick = 0; tick < 500; ++tick) { + CartesianVelocityStep result; + ASSERT_TRUE(advance(result)) << "retreat tick=" << tick; + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(velocity.head<3>().norm(), .04 + 1e-8); + EXPECT_LE(acceleration.head<3>().norm(), options.acceleration + 1e-5); + EXPECT_LE(jerk.head<3>().norm(), *options.linear_jerk + 1e-3); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_GT(q_[6] - wrist_before_reverse, .01); + EXPECT_NEAR(previous.head<3>().norm(), .04, 1e-7); + RecordProperty("reverse_wrist_displacement_rad", std::to_string(q_[6] - wrist_before_reverse)); + } + } else { + EXPECT_GE(failure_tick, 1000); + EXPECT_LT(failure_tick, 1500); + RecordProperty("without_adaptation_failure_tick", failure_tick); + } + } +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveMinimumRatioStopsSmoothlyAndLatchesUntilReset) { + q_ = {.250503734519, 1.1370261797, 1.58375920865, .774603121123, + -2.87240757376, .387646573327, -.395308298864}; + limits_.mutable_adaptive_speed()->set_enable(true); + limits_.mutable_adaptive_speed()->set_lookahead_s(.15); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(.1); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Twist previous = Twist::Zero(), previous_acceleration = Twist::Zero(); + double max_velocity = 0, max_acceleration = 0, max_jerk = 0; + int trigger_tick = -1, settled_tick = -1; + CartesianVelocityStep result; + for (int tick = 0; tick < 3000; ++tick) { + ASSERT_TRUE(advance(result)) << "tick=" << tick; + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + max_velocity = std::max(max_velocity, velocity.head<3>().norm()); + max_acceleration = std::max(max_acceleration, acceleration.head<3>().norm()); + max_jerk = std::max(max_jerk, jerk.head<3>().norm()); + previous = velocity; + previous_acceleration = acceleration; + if (tick == 0) { + EXPECT_LT(velocity.head<3>().norm(), .004); + EXPECT_TRUE(result.stop_reason.ok()); // Startup below 10% is normal. + } + if (!result.stop_reason.ok()) { + EXPECT_EQ(result.stop_reason.code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(result.stop_reason.message.find("adaptive speed ratio below min_speed_ratio"), + std::string::npos); + if (trigger_tick < 0) { + trigger_tick = tick; + EXPECT_FALSE(result.settled); // Must decelerate, not jump to zero. + EXPECT_GT(velocity.head<3>().norm(), 1e-6); + RecordProperty("speed_at_minimum_ratio_m_s", std::to_string(velocity.head<3>().norm())); + auto retreat = target; + retreat.vy = .04; + EXPECT_FALSE(planner_->submit(retreat, options, FrameType::Tool).ok()); + } + EXPECT_FALSE(planner_->submit(target, options, FrameType::Tool).ok()); + if (result.settled) { settled_tick = tick; break; } + } else { + EXPECT_LT(trigger_tick, 0) << "A latched stop must not disappear"; + } + } + EXPECT_GT(trigger_tick, 1000); + ASSERT_GT(settled_tick, trigger_tick); + EXPECT_LT(settled_tick - trigger_tick, 500); + EXPECT_LE(max_velocity, .04 + 1e-8); + EXPECT_GT(max_velocity, .039); + EXPECT_LE(max_acceleration, options.acceleration + 1e-5); + EXPECT_LE(max_jerk, *options.linear_jerk + 1e-3); + EXPECT_NEAR(previous.norm(), 0, 1e-10); + for (double velocity : qd_) EXPECT_NEAR(velocity, 0, 1e-9); + EXPECT_GT(q_[6], -.57); + const double wrist_before_reverse = q_[6]; + for (int tick = 0; tick < 10; ++tick) { + ASSERT_TRUE(advance(result)); + EXPECT_TRUE(result.settled); + EXPECT_FALSE(result.stop_reason.ok()); + } + RecordProperty("minimum_ratio_trigger_tick", trigger_tick); + RecordProperty("minimum_ratio_settled_tick", settled_tick); + RecordProperty("minimum_ratio_max_jerk_m_s3", std::to_string(max_jerk)); + RecordProperty("minimum_ratio_stopped_wrist_rad", std::to_string(q_[6])); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + target.vy = .04; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + for (int tick = 0; tick < 500; ++tick) { + ASSERT_TRUE(advance(result)) << "retreat tick=" << tick; + EXPECT_TRUE(result.stop_reason.ok()); + } + EXPECT_GT(q_[6] - wrist_before_reverse, .01); + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), .04, 1e-7); +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveMinimumRatioDoesNotRejectManualSlowSpeedOrPause) { + limits_.mutable_adaptive_speed()->set_enable(true); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(.1); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + CartesianVelocity target; + target.vy = .02; + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (double scaling : {.05, 0.0, .05, 1.0}) { + SCOPED_TRACE(scaling); + CartesianVelocityStep result; + for (int tick = 0; tick < 500; ++tick) { + ASSERT_TRUE(advance(result, scaling)) << "tick=" << tick; + EXPECT_TRUE(result.stop_reason.ok()); + EXPECT_FALSE(result.settled); // A manual zero multiplier is a pause. + } + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), + .02 * scaling, 1e-7); + } +} + +TEST_F(PinocchioQpSpeedLIntegration, JointBrakingStopsRecordedFirstFailureWithinAccelerationAndPositionLimits) { + q_ = {.582722602717, 1.18224927602, 1.476371331, .30800863072, + -2.97894487049, .408292452313, -.568806827985}; + qd_ = {.435860147793, .0609563589904, -.147285286364, -.702869190529, + -.151214590595, .0319060685236, -.320632525731}; + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + double maximum_acceleration = 0; + CartesianVelocityStep braking; + for (int tick = 0; tick < 100; ++tick) { + braking = planner_->brakeStep(kDt, q_, qd_); + ASSERT_TRUE(braking.status.ok()) << "tick=" << tick << ": " << braking.status.message; + ASSERT_EQ(braking.joint_velocity.velocity.size(), q_.size()); + for (std::size_t joint = 0; joint < q_.size(); ++joint) { + const double next = braking.joint_velocity.velocity[joint]; + const double acceleration = std::abs(next - qd_[joint]) / kDt; + maximum_acceleration = std::max(maximum_acceleration, acceleration); + EXPECT_LE(acceleration, acceleration_limits_[joint] + 1e-6); + EXPECT_LE(std::abs(next), std::abs(qd_[joint]) + 1e-9); + EXPECT_GE(next * qd_[joint], -1e-12); + q_[joint] += next * kDt; + EXPECT_GE(q_[joint], lower_[joint] - 1e-9); + EXPECT_LE(q_[joint], upper_[joint] + 1e-9); + } + // There is no successful Cartesian command to commit at the first + // failure. The brake must use the measured moving state immediately. + if (tick == 0) EXPECT_GT(braking.joint_velocity.velocity[6], qd_[6]); + qd_ = braking.joint_velocity.velocity; + planner_->commitStep(); + if (braking.settled) break; + } + EXPECT_TRUE(braking.settled); + EXPECT_GE(q_[6], -.5693); // Old command held for two ticks ended at -.569448. + for (double velocity : qd_) EXPECT_DOUBLE_EQ(velocity, 0); + RecordProperty("maximum_braking_acceleration_rad_s2", std::to_string(maximum_acceleration)); + RecordProperty("stopped_wrist_position_rad", std::to_string(q_[6])); +} + +TEST_F(PinocchioQpSpeedLIntegration, ReversalPauseResumeAndStopRespectJointBounds) { + // Make nullspace avoidance active even at this pose away from hard limits. + auto policy = solver_->jointLimitPolicy(); + policy.mutable_avoidance()->set_enable(true); + policy.mutable_avoidance()->set_gain(.2); + policy.mutable_avoidance()->set_margin_ratio(.4); + policy.mutable_avoidance()->set_max_push(.1); + solver_->setJointLimitPolicy(policy); + const auto initial_q = q_; + SpeedLOptions options; + options.acceleration = .3; + options.linear_jerk = 20; + options.continuous_linear_reversal = true; + + // Angular reversal stops before restarting: each 0.05 rad/s transition + // takes v/a + a/j = 0.1917 s at a=0.3, j=12. Allow both transitions + // (0.3834 s), followed by at least 100 ms of steady-state observation. + constexpr int kPhaseSamples = 500; + constexpr int kRestSamples = 100; + // Cover a translating and a rotating request, including both signs. + for (int axis : {1, 4}) { + SCOPED_TRACE(axis); + q_ = initial_q; + qd_.assign(q_.size(), 0); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + for (int phase = 0; phase < 5; ++phase) { + SCOPED_TRACE(phase); + Twist target = Twist::Zero(); + if (phase != 4) target[axis] = (phase == 0 ? 1 : -1) * (axis < 3 ? .02 : .05); + const double scaling = phase == 2 ? 0 : 1; + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, + FrameType::Base).ok()); + CartesianVelocityStep result; + std::vector rest_q; + for (int i = 0; i < kPhaseSamples; ++i) { + ASSERT_TRUE(advance(result, scaling)) << "sample=" << i; + if (i == kPhaseSamples - kRestSamples - 1) rest_q = q_; + } + EXPECT_NEAR((common::math::velocityToVector(result.twist_base) - scaling * target).norm(), + 0, 1e-7); + EXPECT_EQ(result.settled, phase == 4); + const Eigen::Map velocity(qd_.data(), qd_.size()); + if (phase == 2 || phase == 4) { + EXPECT_LT(velocity.norm(), 1e-6); + for (std::size_t i = 0; i < q_.size(); ++i) EXPECT_NEAR(q_[i], rest_q[i], 1e-7); + } else { + EXPECT_GT(velocity.norm(), .001); + } + } + } +} +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h new file mode 100644 index 00000000..11c9bfad --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h @@ -0,0 +1,136 @@ +#pragma once + +#include +#include +#include +#include "curves/s_curve/include/s_curve.h" + +namespace cmvr +{ + +enum class LgvCartesianFrame +{ + Base = 0, + Tool = 1 +}; + +/** + * @brief 基于 LgvSCurve 的六维末端在线速度规划器。 + * + * initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。 + * 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。 + * 非连续模式与角速度近反向时,先停稳再反向。 + * 传入零目标平滑停止;相同目标会继续当前曲线,不会每拍重规划。 + * 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。 + * 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。 + */ +class LgvSCurvePlanner +{ +public: + using Twist = Eigen::Matrix; + + void setLinearConstraints(double max_velocity, + double max_acceleration, + double max_jerk); + void setAngularConstraints(double max_velocity, + double max_acceleration, + double max_jerk); + void setLinearTargetReplanThreshold(double threshold); + void setAngularTargetReplanThreshold(double threshold); + + // 连续过零保留加速度;关闭后近反向等待停稳。 + void setContinuousLinearReversal(bool enabled); + bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; } + + // 清除旧曲线,用 Base 系初始速度开始规划。 + void initialize(const Twist& initial_twist = Twist::Zero()); + + // 每周期调用一次。Tool 目标按当拍 base_R_tool 转到 Base 系。 + Twist plan(const Twist& target_twist, LgvCartesianFrame frame, + double dt, const Eigen::Matrix3d& base_R_tool); + + const Twist& getTwistBase() const { return twist_base_; } + const Twist& getAccelerationBase() const { return acceleration_base_; } + const Twist& getJerkBase() const { return jerk_base_; } + bool isMoving() const; + +private: + static constexpr double EPSILON = 1e-12; + static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999; + + // 保存一维速度曲线的运行状态;数学计算由 LgvSCurve 完成。 + struct VelocityState { + struct Sample { + double velocity{0.0}; + double acceleration{0.0}; + double target_velocity{0.0}; + double elapsed_time{0.0}; + bool has_active_profile{false}; + }; + + void setConstraints(double max_velocity, double max_acceleration, double max_jerk); + void setTargetReplanThreshold(double threshold); + void initialize(double velocity = 0.0, double acceleration = 0.0); + void setTargetVelocity(double target_velocity); + double update(double dt); + + double getVelocity() const { return state_.velocity; } + double getAcceleration() const { return state_.acceleration; } + double replanThreshold() const { return target_replan_threshold_; } + std::array limits() const; + bool isSettled() const; + bool isMoving() const; + + private: + void replan(); + + LgvSCurve curve_{1.0, 1.0, 5.0}; + Sample state_; + LgvSCurveVelocityProfile active_profile_; + double target_replan_threshold_{1e-9}; + static constexpr double VELOCITY_THRESHOLD = 1e-6; + }; + + // Cubic Bezier velocity: endpoint accelerations are a0 and zero. + // Derivative control-point norms certify complete v/a/j bounds. + struct DirectionProfile { + std::array control{ + Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), + Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero()}; + double duration{0.0}; + double elapsed{0.0}; + bool active{false}; + bool stopping_for_reversal{false}; + + std::pair sample(double time) const; + bool fits(const std::array& limits) const; + DirectionProfile remaining() const; + }; + + VelocityState linear_velocity_; + VelocityState angular_velocity_; + DirectionProfile linear_direction_profile_; + DirectionProfile angular_direction_profile_; + bool continuous_linear_reversal_{true}; + + Twist twist_base_{Twist::Zero()}; + Twist acceleration_base_{Twist::Zero()}; + Twist jerk_base_{Twist::Zero()}; + double previous_period_{0.0}; + Eigen::Vector3d current_linear_dir_base_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d current_angular_dir_base_{Eigen::Vector3d::Zero()}; + + static void setConstraints(VelocityState& scalar, DirectionProfile& profile, + double velocity, double acceleration, double jerk); + static bool planDirection(const Eigen::Vector3d& velocity, + const Eigen::Vector3d& acceleration, + const Eigen::Vector3d& target, double dt, + const std::array& limits, + DirectionProfile& profile); + static Eigen::Vector3d planVelocity(VelocityState& scalar, DirectionProfile& profile, + Eigen::Vector3d& direction, + const Eigen::Vector3d& target, double dt, + bool continuous_reversal); +}; + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h new file mode 100644 index 00000000..90b7a5f9 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h @@ -0,0 +1,47 @@ +#ifndef CMVR_ES_S_CURVE_PLANNER_CONFIG_H +#define CMVR_ES_S_CURVE_PLANNER_CONFIG_H + +#include +#include + +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/config/config_files.h" + +namespace cmvr::device::cartesian_motion { + +inline void configureSCurvePlannerFromSpeedLConfig( + cmvr::LgvSCurvePlanner& planner, + const config::SpeedLPlannerConfig& config) +{ + using cmvr::common::config::positiveOr; + + // Zero retains the protobuf default; reject bad values before changing the planner. + for (const double value : {config.linear_velocity_max(), config.linear_acceleration_max(), + config.linear_jerk_max(), config.angular_velocity_max(), + config.angular_acceleration_max(), config.angular_jerk_max(), + config.linear_target_replan_threshold(), + config.angular_target_replan_threshold()}) { + if (!std::isfinite(value) || value < 0.0) { + throw std::invalid_argument("speedL limits and thresholds must be finite and non-negative"); + } + } + + planner.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), + positiveOr(config.linear_acceleration_max(), 5.0), + positiveOr(config.linear_jerk_max(), 10.0)); + planner.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), + positiveOr(config.angular_acceleration_max(), 5.0), + positiveOr(config.angular_jerk_max(), 12.0)); + planner.setLinearTargetReplanThreshold( + positiveOr(config.linear_target_replan_threshold(), 1e-4)); + planner.setAngularTargetReplanThreshold( + positiveOr(config.angular_target_replan_threshold(), 1e-4)); + planner.setContinuousLinearReversal(!config.has_continuous_linear_reversal() || + config.continuous_linear_reversal()); + planner.initialize(Eigen::Matrix::Zero()); +} + +} // namespace cmvr::device::cartesian_motion + +#endif // CMVR_ES_S_CURVE_PLANNER_CONFIG_H diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp b/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp new file mode 100644 index 00000000..2095c911 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp @@ -0,0 +1,420 @@ +#include "../include/s_curve_planner.h" + +#include +#include +#include + +namespace cmvr +{ +namespace { +void validateLimits(double velocity, double acceleration, double jerk) +{ + // LgvSCurve's solver treats acceleration/jerk <= 1e-9 as degenerate. + if (!std::isfinite(velocity) || velocity <= 1e-9 || + !std::isfinite(acceleration) || acceleration <= 1e-9 || + !std::isfinite(jerk) || jerk <= 1e-9) { + throw std::invalid_argument("S-curve limits must be finite and greater than 1e-9"); + } +} + +bool withinLimit(double value, double limit) +{ + return std::isfinite(value) && value <= limit * (1.0 + 1e-10); +} +} // namespace + +std::array LgvSCurvePlanner::VelocityState::limits() const +{ + std::array result; + curve_.getConstraints(result[0], result[1], result[2]); + return result; +} + +void LgvSCurvePlanner::VelocityState::setConstraints(double max_velocity, + double max_acceleration, + double max_jerk) +{ + validateLimits(max_velocity, max_acceleration, max_jerk); + if (!withinLimit(std::abs(state_.velocity), max_velocity) || + !withinLimit(std::abs(state_.acceleration), max_acceleration)) { + throw std::invalid_argument("S-curve limits exclude the current velocity or acceleration"); + } + if (limits() == std::array{max_velocity, max_acceleration, max_jerk}) return; + + auto staged = *this; + staged.curve_.setConstraints(max_velocity, max_acceleration, max_jerk); + staged.state_.target_velocity = + std::clamp(state_.target_velocity, -max_velocity, max_velocity); + if (state_.has_active_profile || state_.acceleration != 0.0) staged.replan(); + *this = std::move(staged); +} + +void LgvSCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold) +{ + if (!std::isfinite(threshold) || threshold < 0.0) { + throw std::invalid_argument("S-curve replan threshold must be nonnegative and finite"); + } + target_replan_threshold_ = threshold; +} + +void LgvSCurvePlanner::VelocityState::initialize(double velocity, double acceleration) +{ + const auto bounds = limits(); + if (!withinLimit(std::abs(velocity), bounds[0]) || + !withinLimit(std::abs(acceleration), bounds[1])) { + throw std::invalid_argument("S-curve initial velocity or acceleration exceeds limits"); + } + state_ = Sample{}; + state_.velocity = velocity; + state_.acceleration = acceleration; + state_.target_velocity = velocity; + active_profile_ = LgvSCurveVelocityProfile(); +} + +void LgvSCurvePlanner::VelocityState::setTargetVelocity(double target_velocity) +{ + const double velocity_limit = limits()[0]; + const double new_target = std::clamp(target_velocity, -velocity_limit, velocity_limit); + const bool same_target = + std::abs(new_target - state_.target_velocity) <= target_replan_threshold_; + if (same_target && (state_.has_active_profile || + (std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0))) return; + + state_.target_velocity = new_target; + replan(); +} + +void LgvSCurvePlanner::VelocityState::replan() +{ + const auto candidate = curve_.calculateVelocityProfile( + state_.velocity, state_.target_velocity, state_.acceleration); + const double values[] = {candidate.t1, candidate.t2, candidate.t3, + candidate.total_time, candidate.j1, candidate.j2, candidate.j3, + candidate.v0, candidate.a0, candidate.vf}; + const bool finite = std::all_of(std::begin(values), std::end(values), + [](double value) { return std::isfinite(value); }); + if (!finite || !candidate.valid || candidate.total_time <= 0.0 || + candidate.t1 < 0.0 || candidate.t2 < 0.0 || candidate.t3 < 0.0) { + if (finite && std::abs(state_.velocity - state_.target_velocity) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0) { + state_.has_active_profile = false; + return; + } + throw std::runtime_error("S-curve could not generate a finite feasible velocity profile"); + } + // The mathematical solver must not silently clamp the starting state. + if (std::abs(candidate.v0 - state_.velocity) > 1e-12 || + std::abs(candidate.a0 - state_.acceleration) > 1e-12) { + throw std::runtime_error("S-curve profile changed its initial state"); + } + active_profile_ = candidate; + state_.elapsed_time = 0.0; + state_.has_active_profile = true; +} + +double LgvSCurvePlanner::VelocityState::update(double dt) +{ + if (!state_.has_active_profile) { + if (state_.acceleration != 0.0 || + std::abs(state_.velocity - state_.target_velocity) > VELOCITY_THRESHOLD) { + throw std::runtime_error("S-curve has no active profile for a moving transition"); + } + return state_.velocity; + } + state_.elapsed_time = std::min(state_.elapsed_time + dt, active_profile_.total_time); + if (state_.elapsed_time >= active_profile_.total_time) { + state_.velocity = active_profile_.vf; + state_.acceleration = 0.0; + state_.has_active_profile = false; + } else { + state_.velocity = curve_.getVelocityAtTime(active_profile_, state_.elapsed_time); + state_.acceleration = curve_.getAccelerationAtTime(active_profile_, state_.elapsed_time); + } + if (!std::isfinite(state_.velocity) || !std::isfinite(state_.acceleration)) { + throw std::runtime_error("S-curve produced a non-finite state"); + } + return state_.velocity; +} + +bool LgvSCurvePlanner::VelocityState::isSettled() const +{ + return !state_.has_active_profile && + std::abs(state_.velocity) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0; +} + +bool LgvSCurvePlanner::VelocityState::isMoving() const +{ + return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD; +} + +std::pair +LgvSCurvePlanner::DirectionProfile::sample(double time) const +{ + const double u = std::clamp(time / duration, 0.0, 1.0); + const double r = 1.0 - u; + const Eigen::Vector3d velocity = r*r*r*control[0] + 3*r*r*u*control[1] + + 3*r*u*u*control[2] + u*u*u*control[3]; + const Eigen::Vector3d acceleration = (3.0 / duration) * + (r*r*(control[1]-control[0]) + 2*r*u*(control[2]-control[1]) + + u*u*(control[3]-control[2])); + return {velocity, acceleration}; +} + +bool LgvSCurvePlanner::DirectionProfile::fits(const std::array& bounds) const +{ + if (!std::isfinite(duration) || duration <= 0.0) return false; + std::array acceleration; + for (std::size_t i = 0; i < control.size(); ++i) { + if (!withinLimit(control[i].norm(), bounds[0])) return false; + if (i < acceleration.size()) { + acceleration[i] = (3.0 / duration) * (control[i+1] - control[i]); + if (!withinLimit(acceleration[i].norm(), bounds[1])) return false; + } + } + for (std::size_t i = 0; i < 2; ++i) { + if (!withinLimit(((2.0 / duration) * (acceleration[i+1] - acceleration[i])).norm(), + bounds[2])) return false; + } + return true; +} + +LgvSCurvePlanner::DirectionProfile LgvSCurvePlanner::DirectionProfile::remaining() const +{ + auto result = *this; + auto work = control; + const double u = std::clamp(elapsed / duration, 0.0, 1.0); + for (std::size_t level = 1; level < control.size(); ++level) { + for (std::size_t i = 0; i < control.size() - level; ++i) { + work[i] = (1.0 - u) * work[i] + u * work[i+1]; + } + result.control[control.size()-level-1] = work[control.size()-level-1]; + } + result.duration -= elapsed; + result.elapsed = 0.0; + return result; +} + +void LgvSCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile, + double velocity, double acceleration, double jerk) +{ + validateLimits(velocity, acceleration, jerk); + if (scalar.limits() == std::array{velocity, acceleration, jerk}) return; + if (profile.active && !profile.remaining().fits({velocity, acceleration, jerk})) { + throw std::invalid_argument("S-curve limits exclude the remaining direction transition"); + } + // While a vector curve is active the scalar state is dormant at zero. + scalar.setConstraints(velocity, acceleration, jerk); +} + +void LgvSCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk); +} + +void LgvSCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk); +} + +void LgvSCurvePlanner::setLinearTargetReplanThreshold(double threshold) +{ + linear_velocity_.setTargetReplanThreshold(threshold); +} + +void LgvSCurvePlanner::setAngularTargetReplanThreshold(double threshold) +{ + angular_velocity_.setTargetReplanThreshold(threshold); +} + +void LgvSCurvePlanner::setContinuousLinearReversal(bool enabled) +{ + if (continuous_linear_reversal_ == enabled) return; + if (!enabled && !linear_direction_profile_.active) { + const double velocity = linear_velocity_.getVelocity(); + const double acceleration = linear_velocity_.getAcceleration(); + if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) { + linear_velocity_.initialize(-velocity, -acceleration); + current_linear_dir_base_ = -current_linear_dir_base_; + } + } + if (enabled) linear_direction_profile_.stopping_for_reversal = false; + continuous_linear_reversal_ = enabled; +} + +void LgvSCurvePlanner::initialize(const Twist& initial_twist) +{ + const Eigen::Vector3d v0 = initial_twist.head<3>(); + const Eigen::Vector3d w0 = initial_twist.tail<3>(); + const double v0_norm = v0.norm(); + const double w0_norm = w0.norm(); + if (!initial_twist.allFinite() || !std::isfinite(v0_norm) || !std::isfinite(w0_norm)) { + throw std::invalid_argument("S-curve initial twist must be finite"); + } + auto staged = *this; + staged.linear_velocity_.initialize(v0_norm, 0.0); + staged.angular_velocity_.initialize(w0_norm, 0.0); + staged.linear_direction_profile_ = DirectionProfile{}; + staged.angular_direction_profile_ = DirectionProfile{}; + staged.twist_base_ = initial_twist; + staged.acceleration_base_.setZero(); + staged.jerk_base_.setZero(); + staged.previous_period_ = 0.0; + staged.current_linear_dir_base_.setZero(); + staged.current_angular_dir_base_.setZero(); + if (v0_norm > EPSILON) staged.current_linear_dir_base_ = v0 / v0_norm; + if (w0_norm > EPSILON) staged.current_angular_dir_base_ = w0 / w0_norm; + *this = std::move(staged); +} + +bool LgvSCurvePlanner::planDirection(const Eigen::Vector3d& velocity, + const Eigen::Vector3d& acceleration, + const Eigen::Vector3d& target, double dt, + const std::array& bounds, + DirectionProfile& profile) +{ + const double delta = (target - velocity).norm(); + const double a = acceleration.norm(); + // Necessary lower bounds; feasibility is not monotone in duration because + // P1 = v0 + T*a0/3 can leave the velocity ball when T grows. + const double a_over_j = a / bounds[2]; + const double delta_over_j = 6.0 * (delta / bounds[2]); + const double denominator = std::hypot(2.0 * a_over_j, std::sqrt(delta_over_j)) + + 2.0 * a_over_j; + const double jerk_duration = denominator > 0.0 ? delta_over_j / denominator : 0.0; + double duration = std::max({1e-9, std::min(dt, 1e-6), a_over_j, jerk_duration, + 3.0 * delta / (bounds[1] + a)}); + for (int attempt = 0; attempt < 50 && std::isfinite(duration); ++attempt) { + DirectionProfile candidate; + candidate.control = {velocity, velocity + (duration / 3.0) * acceleration, + target, target}; + candidate.duration = duration; + candidate.active = true; + candidate.stopping_for_reversal = profile.stopping_for_reversal; + if (candidate.fits(bounds)) { + profile = std::move(candidate); + return true; + } + duration *= 1.18; + } + return false; +} + +Eigen::Vector3d LgvSCurvePlanner::planVelocity(VelocityState& scalar, + DirectionProfile& profile, + Eigen::Vector3d& direction, + const Eigen::Vector3d& target, double dt, + bool continuous_reversal) +{ + const auto bounds = scalar.limits(); + Eigen::Vector3d desired = target; + const double target_norm = target.norm(); + if (target_norm > bounds[0]) desired *= bounds[0] / target_norm; + + Eigen::Vector3d velocity = direction * scalar.getVelocity(); + Eigen::Vector3d acceleration = direction * scalar.getAcceleration(); + if (profile.active) { + const auto state = profile.sample(profile.elapsed); + velocity = state.first; + acceleration = state.second; + if (!continuous_reversal && velocity.norm() > EPSILON && desired.norm() > EPSILON && + velocity.normalized().dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD) { + profile.stopping_for_reversal = true; + } + } + if (profile.stopping_for_reversal) desired.setZero(); + + if (!profile.active) { + if (velocity.isZero(0.0) && acceleration.isZero(0.0)) { + if (desired.norm() > EPSILON) direction = desired.normalized(); + scalar.setTargetVelocity(desired.norm()); + return direction * scalar.update(dt); + } + const double signed_target = direction.dot(desired); + const bool collinear = (desired - signed_target * direction).norm() <= + 1e-12 * desired.norm(); + const bool reverse = desired.norm() > EPSILON && + direction.dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD; + if (desired.norm() <= EPSILON || (!continuous_reversal && reverse) || + (collinear && (continuous_reversal || signed_target >= 0.0))) { + scalar.setTargetVelocity((!continuous_reversal && reverse) ? 0.0 : signed_target); + const auto result = direction * scalar.update(dt); + if (profile.stopping_for_reversal && scalar.isSettled()) { + profile.stopping_for_reversal = false; + } + return result; + } + } + + if (!profile.active || + (desired - profile.control.back()).norm() > scalar.replanThreshold()) { + if (planDirection(velocity, acceleration, desired, dt, bounds, profile)) { + scalar.initialize(); + } + } + // A rejected candidate leaves the certified old curve running. In particular, + // preserve its acceleration instead of holding one velocity sample. + if (!profile.active) return direction * scalar.update(dt); + profile.elapsed = std::min(profile.elapsed + dt, profile.duration); + velocity = profile.sample(profile.elapsed).first; + if (profile.elapsed >= profile.duration) { + profile.active = false; + const double speed = velocity.norm(); + scalar.initialize(speed, 0.0); + if (speed > EPSILON) direction = velocity / speed; + if (speed <= EPSILON) profile.stopping_for_reversal = false; + } + return velocity; +} + +LgvSCurvePlanner::Twist +LgvSCurvePlanner::plan(const Twist& target_twist, LgvCartesianFrame frame, + double dt, const Eigen::Matrix3d& base_R_tool) +{ + // Smaller periods cannot reliably support command differences in double precision. + if (!std::isfinite(dt) || dt < 1e-9) { + throw std::invalid_argument("S-curve period must be finite and at least 1e-9 seconds"); + } + if ((frame != LgvCartesianFrame::Base && frame != LgvCartesianFrame::Tool) || + !target_twist.allFinite() || + (frame == LgvCartesianFrame::Tool && !base_R_tool.allFinite())) { + throw std::invalid_argument("invalid S-curve target, frame or tool rotation"); + } + Twist target_base = target_twist; + if (frame == LgvCartesianFrame::Tool) { + target_base.head<3>() = base_R_tool * target_twist.head<3>(); + target_base.tail<3>() = base_R_tool * target_twist.tail<3>(); + } + if (!target_base.allFinite() || !std::isfinite(target_base.head<3>().norm()) || + !std::isfinite(target_base.tail<3>().norm())) { + throw std::invalid_argument("S-curve target magnitude must be finite"); + } + auto staged = *this; + staged.twist_base_.head<3>() = planVelocity(staged.linear_velocity_, + staged.linear_direction_profile_, staged.current_linear_dir_base_, + target_base.head<3>(), dt, continuous_linear_reversal_); + staged.twist_base_.tail<3>() = planVelocity(staged.angular_velocity_, + staged.angular_direction_profile_, staged.current_angular_dir_base_, + target_base.tail<3>(), dt, false); + // Keep the public diagnostics based on actual output commands. + staged.acceleration_base_ = (staged.twist_base_ - twist_base_) / dt; + // Acceleration samples are averages over intervals, located at their centers. + staged.jerk_base_ = (staged.acceleration_base_ - acceleration_base_) / + (0.5 * previous_period_ + 0.5 * dt); + staged.previous_period_ = dt; + if (!staged.twist_base_.allFinite() || !staged.acceleration_base_.allFinite() || + !staged.jerk_base_.allFinite()) { + throw std::runtime_error("S-curve produced a non-finite command"); + } + *this = std::move(staged); + return twist_base_; +} + +bool LgvSCurvePlanner::isMoving() const +{ + return linear_direction_profile_.active || angular_direction_profile_.active || + linear_velocity_.isMoving() || angular_velocity_.isMoving(); +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp b/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp new file mode 100644 index 00000000..d17f5444 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp @@ -0,0 +1,320 @@ +#include +#include +#include +#include + +#include +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" + +namespace cmvr { +namespace { +using Twist = LgvSCurvePlanner::Twist; +constexpr double dt = .001; +Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; } +struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; }; +Motion reverse(bool continuous, int approach_ticks) { + LgvSCurvePlanner planner; + planner.setLinearConstraints(.55, 5, 10); + planner.setContinuousLinearReversal(continuous); + planner.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero()); + for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + planner.setLinearConstraints(.55, 3, 10); + Motion result; + double position = 0; + for (int i = 1; i <= 1500; ++i) { + const auto v = planner.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + position += v.y() * dt; + result.peak = std::max(result.peak, position); + if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt; + if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt; + if (continuous) { + EXPECT_LE(planner.getAccelerationBase().norm(), 3.0 + 1e-7); + EXPECT_LE(planner.getJerkBase().norm(), 10.0 + 1e-6); + EXPECT_NEAR(v.x(), 0, 1e-12); + EXPECT_NEAR(v.z(), 0, 1e-12); + } + } + EXPECT_NEAR(planner.getTwistBase().y(), -.08, 1e-9); + return result; +} +TEST(LgvSCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) { + for (const int ticks : {0, 80, 120}) { + SCOPED_TRACE(ticks); + const auto legacy = reverse(false, ticks); + const auto continuous = reverse(true, ticks); + EXPECT_GT(continuous.reverse_time, 0); + EXPECT_LT(continuous.reverse_time, legacy.reverse_time); + EXPECT_LT(continuous.return_time, legacy.return_time); + EXPECT_LT(continuous.peak, legacy.peak); + } +} +TEST(LgvSCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) { + LgvSCurvePlanner planner; + planner.setLinearConstraints(1, 1, 4); + planner.initialize(y(.02)); + for (int i = 0; i < 100; ++i) planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_NEAR(planner.getTwistBase().y(), 0, 1e-12); + EXPECT_TRUE(planner.isMoving()); + EXPECT_LT(planner.getAccelerationBase().y(), -.39); + EXPECT_LT(planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003); +} +TEST(LgvSCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) { + for (double v : {.08, -.08}) { + LgvSCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + planner.initialize(y(v)); + for (int i = 0; i < 1000; ++i) { + EXPECT_GE(planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12); + } + EXPECT_FALSE(planner.isMoving()); + EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12); + } +} +TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) { + for (bool continuous : {true, false}) { + for (int offset : {0, 3}) { + for (bool accelerating : {false, true}) { + SCOPED_TRACE(::testing::Message() << "continuous=" << continuous + << " angular=" << (offset == 3) << " accelerating=" << accelerating); + LgvSCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + planner.setAngularConstraints(1, 3, 10); + planner.setContinuousLinearReversal(continuous); + Twist initial = Twist::Zero(), target = Twist::Zero(); + initial[offset + 1] = .08; + target[offset] = .08; + if (accelerating) { + planner.initialize(); + planner.plan(initial, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + ASSERT_LT(planner.getTwistBase().norm(), 1e-3); + ASSERT_GT(planner.getAccelerationBase().norm(), 1e-3); + } else { + planner.initialize(initial); + } + double max_acceleration = 0, max_jerk = 0; + Twist previous = planner.getTwistBase(); + Twist previous_acceleration = planner.getAccelerationBase(); + for (int i = 0; i < 1000; ++i) { + const auto v = planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const Twist acceleration = (v - previous) / dt; + const Twist jerk = (acceleration - previous_acceleration) / dt; + EXPECT_LE(acceleration.norm(), 3 + 1e-6); + EXPECT_LE(jerk.norm(), 10 + 1e-5); + previous = v; + previous_acceleration = acceleration; + max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm()); + max_jerk = std::max(max_jerk, planner.getJerkBase().norm()); + } + EXPECT_LE(max_acceleration, 3 + 1e-6); + EXPECT_LE(max_jerk, 10 + 1e-6); + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + + // Same-axis magnitude planning must keep moving when the target + // has the same direction, including legacy linear streaming. + target *= 1.5; + for (int i = 0; i < 500; ++i) { + EXPECT_GE(planner.plan(target, LgvCartesianFrame::Base, dt, + Eigen::Matrix3d::Identity())[offset], .08 - 1e-9); + } + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + + if (offset == 3) { + target = -target; + max_acceleration = max_jerk = 0; + for (int i = 0; i < 1000; ++i) { + planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm()); + max_jerk = std::max(max_jerk, planner.getJerkBase().norm()); + } + EXPECT_LE(max_acceleration, 3 + 1e-6); + EXPECT_LE(max_jerk, 10 + 1e-6); + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + } + } + } + } +} + +TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) { + for (bool continuous : {true, false}) { + for (int offset : {0, 3}) { + for (double max_velocity : {.08, 1.}) { + SCOPED_TRACE(::testing::Message() << "continuous=" << continuous + << " angular=" << (offset == 3) << " vmax=" << max_velocity); + LgvSCurvePlanner planner; + planner.setLinearConstraints(max_velocity, 3, 10); + planner.setAngularConstraints(max_velocity, 3, 10); + planner.setContinuousLinearReversal(continuous); + Twist target = Twist::Zero(); + target[offset] = .08; + planner.initialize(target); + Twist previous = target, previous_acceleration = Twist::Zero(); + double min_speed = .08; + for (int i = 0; i < 3000; ++i) { + // First reproduce the .01-rad step, then keep rotating the Tool. + const double angle = .01 + .2 * i * dt; + Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity(); + rotation(0, 0) = rotation(1, 1) = std::cos(angle); + rotation(0, 1) = -std::sin(angle); + rotation(1, 0) = std::sin(angle); + const Twist v = planner.plan(target, LgvCartesianFrame::Tool, dt, rotation); + const Twist a = (v - previous) / dt; + const Twist j = (a - previous_acceleration) / dt; + EXPECT_LE(v.norm(), max_velocity + 1e-9); + EXPECT_LE(a.norm(), 3 + 1e-6); + EXPECT_LE(j.norm(), 10 + 1e-5); + min_speed = std::min(min_speed, v.norm()); + previous = v; + previous_acceleration = a; + } + EXPECT_GT(min_speed, .072); + for (int i = 0; i < 1500; ++i) { + const Twist v = planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt, + Eigen::Matrix3d::Identity()); + const Twist a = (v - previous) / dt; + EXPECT_LE(a.norm(), 3 + 1e-6); + EXPECT_LE(((a - previous_acceleration) / dt).norm(), 10 + 1e-5); + previous = v; + previous_acceleration = a; + } + EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-10); + EXPECT_FALSE(planner.isMoving()); + } + } + } +} + +TEST(LgvSCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) { + for (const int reverse_ticks : {150, 250, 500}) { + SCOPED_TRACE(reverse_ticks); + LgvSCurvePlanner reference; + reference.setLinearConstraints(1, 3, 10); + reference.initialize(y(.08)); + for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + ASSERT_LT(reference.getTwistBase().y(), 0); + auto streaming = reference; + streaming.setContinuousLinearReversal(false); + EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12); + for (int i = 0; i < 500; ++i) { + const auto expected = reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual = streaming.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_NEAR((actual - expected).norm(), 0, 1e-9); + EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6); + } + } +} + +TEST(LgvSCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) { + LgvSCurvePlanner planner; + planner.setLinearConstraints(1, 3, .01); + planner.initialize(y(.08)); + Twist target = Twist::Zero(); + target.x() = .08 * std::sin(1e-4); + target.y() = .08 * std::cos(1e-4); + for (int i = 0; i < 1000; ++i) { + planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_LE(planner.getAccelerationBase().norm(), 3 + 1e-7); + EXPECT_LE(planner.getJerkBase().norm(), .01 + 1e-7); + } + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-10); +} + +TEST(LgvSCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) { + LgvSCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + for (int i = 0; i < 100; ++i) { + const double period = i % 2 ? .0005 : .001; + planner.plan(y(.08), LgvCartesianFrame::Base, period, Eigen::Matrix3d::Identity()); + EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7); + } +} + +TEST(LgvSCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) { + LgvSCurvePlanner actual; + actual.setLinearConstraints(.05, 1e-6, .001); + actual.initialize(y(.0499995)); + actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + auto reference = actual; + // Removing the small acceleration with this jerk would exceed vmax. + // A numerical "near zero" test must not accept and freeze this state. + EXPECT_THROW(actual.setLinearConstraints(.05, 1e-6, 1e-8), std::runtime_error); + for (int i = 0; i < 1000; ++i) { + const Twist a = actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const Twist b = reference.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_DOUBLE_EQ((a - b).norm(), 0); + EXPECT_LE(actual.getJerkBase().norm(), .001 + 1e-7); + } + EXPECT_NEAR(actual.getTwistBase().y(), .05, 1e-12); +} + +TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) { + LgvSCurvePlanner seed; + seed.setLinearConstraints(1, 3, 10); + seed.setAngularConstraints(1, 3, 10); + Twist target = y(.08); + target[5] = .12; + for (int i = 0; i < 80; ++i) + seed.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + + const auto expect_unchanged = [&](auto operation) { + auto expected = seed; + auto actual = seed; + EXPECT_THROW(operation(actual), std::invalid_argument); + const auto compare_state = [&] { + EXPECT_DOUBLE_EQ((actual.getTwistBase() - expected.getTwistBase()).norm(), 0); + EXPECT_DOUBLE_EQ((actual.getAccelerationBase() - expected.getAccelerationBase()).norm(), 0); + EXPECT_DOUBLE_EQ((actual.getJerkBase() - expected.getJerkBase()).norm(), 0); + EXPECT_EQ(actual.isMoving(), expected.isMoving()); + EXPECT_EQ(actual.continuousLinearReversalEnabled(), expected.continuousLinearReversalEnabled()); + }; + compare_state(); + for (int i = 0; i < 200; ++i) { + const auto expected_twist = expected.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual_twist = actual.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_DOUBLE_EQ((actual_twist - expected_twist).norm(), 0); + compare_state(); + } + }; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + for (double invalid : {-1., 0., nan, inf}) { + SCOPED_TRACE(::testing::Message() << "invalid=" << invalid); + for (int index = 0; index < 3; ++index) { + SCOPED_TRACE(index); + double limits[] = {1, 3, 10}; + limits[index] = invalid; + expect_unchanged([&](auto& p) { p.setLinearConstraints(limits[0], limits[1], limits[2]); }); + expect_unchanged([&](auto& p) { p.setAngularConstraints(limits[0], limits[1], limits[2]); }); + } + expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); }); + if (invalid != 0) { + expect_unchanged([&](auto& p) { p.setLinearTargetReplanThreshold(invalid); }); + expect_unchanged([&](auto& p) { p.setAngularTargetReplanThreshold(invalid); }); + } + } + for (double invalid : {nan, inf}) { + for (int index : {0, 5}) { + Twist invalid_twist = target; + invalid_twist[index] = invalid; + expect_unchanged([&](auto& p) { p.initialize(invalid_twist); }); + expect_unchanged([&](auto& p) { p.plan(invalid_twist, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); }); + } + Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity(); + invalid_rotation(1, 2) = invalid; + expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Tool, dt, invalid_rotation); }); + } + // Over-limit initialization must not clamp only the internal scalar or + // reset linear motion before discovering an invalid angular component. + for (int index : {0, 5}) { + Twist initial = y(.2); + initial[index] = 2; + expect_unchanged([&](auto& p) { p.initialize(initial); }); + } + expect_unchanged([&](auto& p) { p.setLinearConstraints(.001, 3, 10); }); + expect_unchanged([&](auto& p) { p.setLinearConstraints(1, .01, 10); }); + expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); }); + expect_unchanged([&](auto& p) { p.plan(target, static_cast(9), dt, Eigen::Matrix3d::Identity()); }); +} + +} +} diff --git a/cmvr-es/algorithms/planner/joint/joint_path_planner.h b/cmvr-es/algorithms/planner/joint/joint_path_planner.h new file mode 100644 index 00000000..fc2f2bdc --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/joint_path_planner.h @@ -0,0 +1,62 @@ +#ifndef CMVR_ES_JOINT_PATH_PLANNER_H +#define CMVR_ES_JOINT_PATH_PLANNER_H + +#include +#include +#include +#include + +namespace cmvr { + +using JointPath = std::vector>; + +struct JointPathRequest { + // All vectors use the same joint order and radians. Bounded revolute joints + // only; continuous joints require a different state space. + std::vector start; + std::vector goal; + std::vector lower_bounds; + std::vector upper_bounds; + + // Required: return true only for a valid configuration. Capture a stable + // collision scene for the entire request. Callbacks run on the calling + // thread; concurrent requests must not share a mutable collision checker. + std::function&)> is_state_valid; + std::function is_cancelled; +}; + +enum class JointPathStatus { + Success, + InvalidRequest, + InvalidStart, + InvalidGoal, + TimedOut, + Cancelled, + ValidationError, + PlanningFailed, +}; + +struct JointPathResult { + JointPathStatus status{JointPathStatus::InvalidRequest}; + // Empty on failure. Success contains both exact endpoints, without timing, + // smoothing, or motor commands. An unchanged target contains one point. + JointPath waypoints; + std::string message; + double planning_time_s{0.0}; + std::size_t validity_checks{0}; + + bool ok() const { return status == JointPathStatus::Success; } +}; + +class JointPathPlanner { +public: + virtual ~JointPathPlanner() = default; + + // Synchronous planning. Cancellation is cooperative: callbacks must return + // promptly and cannot be forcibly interrupted. + virtual JointPathResult plan(const JointPathRequest& request) const = 0; +}; + +} // namespace cmvr + +#endif // CMVR_ES_JOINT_PATH_PLANNER_H diff --git a/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h b/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h new file mode 100644 index 00000000..b16a3452 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h @@ -0,0 +1,48 @@ +#ifndef CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H +#define CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H + +#include +#include + +#include "algorithms/planner/joint/joint_path_planner.h" +#include "algorithms/planner/joint/ompl/include/rrt_connect.h" +#include "cmvr/config/joint_motion_config.pb.h" + +namespace cmvr { + +class JointPathPlannerFactory { +public: + static std::shared_ptr create( + const config::JointPathConfig& cfg) + { + switch (cfg.algorithm()) { + case config::RRT_CONNECT: { + const auto& rrt_connect = cfg.rrt_connect(); + RrtConnectOptions options; + if (rrt_connect.has_timeout_s()) { + options.timeout_s = rrt_connect.timeout_s(); + } + if (rrt_connect.has_range_rad()) { + options.range_rad = rrt_connect.range_rad(); + } + if (rrt_connect.has_collision_check_step_rad()) { + options.collision_check_step_rad = rrt_connect.collision_check_step_rad(); + } + if (!std::isfinite(options.timeout_s) || options.timeout_s <= 0.0 || + !std::isfinite(options.range_rad) || options.range_rad <= 0.0 || + !std::isfinite(options.collision_check_step_rad) || + options.collision_check_step_rad <= 0.0) { + return nullptr; + } + return std::make_shared(options); + } + case config::JOINT_PATH_ALGORITHM_UNKNOWN: + default: + return nullptr; + } + } +}; + +} // namespace cmvr + +#endif // CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h b/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h new file mode 100644 index 00000000..f533842b --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h @@ -0,0 +1,28 @@ +#pragma once + +#include "algorithms/planner/joint/joint_path_planner.h" + +namespace cmvr { + +struct RrtConnectOptions { + double timeout_s{1.0}; + // Maximum tree extension in the Euclidean joint-space metric. + double range_rad{0.2}; + // Maximum per-joint increment between collision samples on each edge. + // This is discrete checking, not a continuous collision guarantee. + double collision_check_step_rad{0.02}; +}; + +class RrtConnect final : public JointPathPlanner { +public: + explicit RrtConnect(const RrtConnectOptions& options = {}); + + // Each call owns a fresh OMPL context. Timeout/cancellation are cooperative: + // user callbacks must return promptly and cannot be forcibly interrupted. + JointPathResult plan(const JointPathRequest& request) const override; + +private: + RrtConnectOptions options_; +}; + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp b/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp new file mode 100644 index 00000000..8d287459 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp @@ -0,0 +1,262 @@ +#include "algorithms/planner/joint/ompl/include/rrt_connect.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace cmvr { +namespace { + +namespace ob = ompl::base; +namespace og = ompl::geometric; +using Clock = std::chrono::steady_clock; + +constexpr double kMaxSegmentsPerEdge = 1000000.0; + +// Use an absolute, per-joint resolution instead of a fraction of the entire +// state-space extent, so adding joints does not coarsen collision checking. +class JointMotionValidator final : public ob::MotionValidator { +public: + JointMotionValidator(const ob::SpaceInformationPtr& si, double step) + : ob::MotionValidator(si), step_(step) {} + + bool checkMotion(const ob::State* from, const ob::State* to) const override + { + std::pair last_valid{nullptr, 0.0}; + return checkMotion(from, to, last_valid); + } + + bool checkMotion(const ob::State* from, const ob::State* to, + std::pair& last_valid) const override + { + const auto* a = from->as(); + const auto* b = to->as(); + double delta = 0.0; + for (unsigned int i = 0; i < si_->getStateDimension(); ++i) { + delta = std::max(delta, std::abs(b->values[i] - a->values[i])); + } + const auto segments = static_cast( + std::max(1.0, std::ceil(delta / step_))); + ob::ScopedState<> sample(si_->getStateSpace()); + for (std::size_t i = 1; i <= segments; ++i) { + const double fraction = static_cast(i) / segments; + si_->getStateSpace()->interpolate(from, to, fraction, sample.get()); + if (!si_->isValid(sample.get())) { + last_valid.second = static_cast(i - 1) / segments; + if (last_valid.first) { + si_->getStateSpace()->interpolate( + from, to, last_valid.second, last_valid.first); + } + ++invalid_; + return false; + } + } + ++valid_; + return true; + } + +private: + double step_; +}; + +bool positiveFinite(double value) +{ + return std::isfinite(value) && value > 0.0; +} + +} // namespace + +RrtConnect::RrtConnect(const RrtConnectOptions& options) + : options_(options) +{ +} + +JointPathResult RrtConnect::plan(const JointPathRequest& request) const +{ + const auto begin = Clock::now(); + JointPathResult result; + const auto finish = [&](JointPathStatus status, const std::string& message) { + result.status = status; + result.message = message; + result.planning_time_s = std::chrono::duration(Clock::now() - begin).count(); + if (status != JointPathStatus::Success) { + result.waypoints.clear(); + } + return result; + }; + + const auto dof = request.start.size(); + if (dof == 0 || dof > std::numeric_limits::max() || + request.goal.size() != dof || request.lower_bounds.size() != dof || + request.upper_bounds.size() != dof || !request.is_state_valid) { + return finish(JointPathStatus::InvalidRequest, + "Matching non-empty joint vectors and a validity callback are required"); + } + if (!positiveFinite(options_.timeout_s) || !positiveFinite(options_.range_rad) || + !positiveFinite(options_.collision_check_step_rad)) { + return finish(JointPathStatus::InvalidRequest, + "Timeout, range, and collision checking step must be finite and positive"); + } + double extent = 0.0; + for (std::size_t i = 0; i < dof; ++i) { + const double lower = request.lower_bounds[i]; + const double upper = request.upper_bounds[i]; + const double width = upper - lower; + if (!std::isfinite(lower) || !std::isfinite(upper) || + !positiveFinite(width) || + width / options_.collision_check_step_rad > kMaxSegmentsPerEdge || + !std::isfinite(request.start[i]) || !std::isfinite(request.goal[i])) { + return finish(JointPathStatus::InvalidRequest, + "Joint values/bounds are invalid or checking resolution is too small"); + } + extent = std::hypot(extent, width); + } + // OMPL's real-vector metric squares individual joint differences. + if (!std::isfinite(extent) || extent > std::sqrt(std::numeric_limits::max())) { + return finish(JointPathStatus::InvalidRequest, "Joint-space extent is too large"); + } + const auto in_bounds = [&](const std::vector& q) { + for (std::size_t i = 0; i < dof; ++i) { + if (q[i] < request.lower_bounds[i] || q[i] > request.upper_bounds[i]) { + return false; + } + } + return true; + }; + if (!in_bounds(request.start)) { + return finish(JointPathStatus::InvalidStart, "Start is outside joint limits"); + } + if (!in_bounds(request.goal)) { + return finish(JointPathStatus::InvalidGoal, "Goal is outside joint limits"); + } + + bool cancelled = false; + bool timed_out = false; + std::string callback_error; + const auto stopped = [&] { + if (cancelled || timed_out || !callback_error.empty()) { + return true; + } + try { + cancelled = request.is_cancelled && request.is_cancelled(); + } catch (const std::exception& exception) { + callback_error = std::string("Cancellation callback failed: ") + exception.what(); + } catch (...) { + callback_error = "Cancellation callback failed"; + } + timed_out = std::chrono::duration(Clock::now() - begin).count() >= options_.timeout_s; + return cancelled || timed_out || !callback_error.empty(); + }; + const auto stop_result = [&] { + if (!callback_error.empty()) { + return finish(JointPathStatus::ValidationError, callback_error); + } + return cancelled ? finish(JointPathStatus::Cancelled, "Planning cancelled") + : finish(JointPathStatus::TimedOut, "Planning time budget exhausted"); + }; + // Never let user exceptions unwind through OMPL's search allocations. + const auto valid = [&](const std::vector& q) { + if (stopped() || !in_bounds(q)) { + return false; + } + bool accepted = false; + try { + ++result.validity_checks; + accepted = request.is_state_valid(q); + } catch (const std::exception& exception) { + callback_error = std::string("Validity callback failed: ") + exception.what(); + } catch (...) { + callback_error = "Validity callback failed"; + } + return !stopped() && accepted; + }; + + if (!valid(request.start)) { + return stopped() ? stop_result() + : finish(JointPathStatus::InvalidStart, "Start failed validity checking"); + } + if (!valid(request.goal)) { + return stopped() ? stop_result() + : finish(JointPathStatus::InvalidGoal, "Goal failed validity checking"); + } + if (request.start == request.goal) { + result.waypoints.push_back(request.start); + return finish(JointPathStatus::Success, "Start already equals goal"); + } + + try { + auto space = std::make_shared(static_cast(dof)); + ob::RealVectorBounds bounds(static_cast(dof)); + bounds.low = request.lower_bounds; + bounds.high = request.upper_bounds; + space->setBounds(bounds); + + og::SimpleSetup setup(space); + setup.setStateValidityChecker([&](const ob::State* state) { + const auto* values = state->as()->values; + return valid(std::vector(values, values + dof)); + }); + setup.getSpaceInformation()->setMotionValidator( + std::make_shared( + setup.getSpaceInformation(), options_.collision_check_step_rad)); + ob::ScopedState<> start(space), goal(space); + for (std::size_t i = 0; i < dof; ++i) { + start[i] = request.start[i]; + goal[i] = request.goal[i]; + } + // // 优先直连,整段通过现有碰撞检测后直接返回。 + // setup.getSpaceInformation()->setup(); + // const bool direct = setup.getSpaceInformation()->checkMotion(start.get(), goal.get()); + // if (stopped()) { + // return stop_result(); + // } + // if (direct) { + // result.waypoints = {request.start, request.goal}; + // return finish(JointPathStatus::Success, "Direct joint path found"); + // } + + setup.setStartAndGoalStates(start, goal); + auto planner = std::make_shared(setup.getSpaceInformation()); + planner->setRange(options_.range_rad); + setup.setPlanner(planner); + const auto status = setup.solve(ob::PlannerTerminationCondition(stopped)); + if (stopped()) { + return stop_result(); + } + // PlannerStatus::operator bool also accepts approximate solutions. + if (status != ob::PlannerStatus::EXACT_SOLUTION || !setup.haveExactSolutionPath()) { + return finish(JointPathStatus::PlanningFailed, "No exact path to the requested goal"); + } + auto& path = setup.getSolutionPath(); + setup.getPathSimplifier()->ropeShortcutPath(path); + if (!path.check()) { + return stopped() ? stop_result() + : finish(JointPathStatus::PlanningFailed, "Final path failed validation"); + } + for (const auto* state : path.getStates()) { + const auto* values = state->as()->values; + result.waypoints.emplace_back(values, values + dof); + } + if (result.waypoints.empty() || result.waypoints.front() != request.start || + result.waypoints.back() != request.goal) { + return finish(JointPathStatus::PlanningFailed, "Path endpoints do not match the request"); + } + if (stopped()) { + return stop_result(); + } + return finish(JointPathStatus::Success, "Exact RRTConnect path found"); + } catch (const std::exception& exception) { + return finish(JointPathStatus::PlanningFailed, exception.what()); + } +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp new file mode 100644 index 00000000..ca36bba8 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp @@ -0,0 +1,222 @@ +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "algorithms/collision_detection/include/collision_checker.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { +namespace { + +class RrtConnectSelfCollisionTest : public ::testing::Test { +protected: + void SetUp() override + { + const std::vector joints{ + "right_arm_J1", "right_arm_J2", "right_arm_J3", "right_arm_J4", + "right_arm_J5", "right_arm_J6", "right_arm_J7"}; + CollisionOptions options; + options.ignored_pairs = {{"arm_link_5_2", "arm_link_7_2"}, + {"body_link", "arm_link_2_2"}}; + std::string error; + ASSERT_TRUE(checker_.init( + std::string(CMVR_ES_SOURCE_DIR) + "/model/gen2/collision/robot_collision.urdf", + joints, options, &error)) << error; + request_.start = {0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0}; + request_.goal = request_.start; + request_.goal[0] += 0.1; + // These seven bounded joints in the Gen2 collision URDF use +/- pi. + request_.lower_bounds.assign(7, -3.141592653589793); + request_.upper_bounds.assign(7, 3.141592653589793); + request_.is_state_valid = [&](const auto& q) { + const auto result = checker_.check(q); + return result.valid && !result.in_collision && result.minimum_distance_m > 0.02; + }; + cfg_.set_algorithm(config::RRT_CONNECT); + cfg_.mutable_rrt_connect()->set_timeout_s(2.0); + cfg_.mutable_rrt_connect()->set_collision_check_step_rad(0.01); + } + + CollisionChecker checker_; + JointPathRequest request_; + config::JointPathConfig cfg_; +}; + +TEST_F(RrtConnectSelfCollisionTest, PlansWithExistingGen2CollisionChecker) +{ + ASSERT_TRUE(request_.is_state_valid(request_.start)); + ASSERT_TRUE(request_.is_state_valid(request_.goal)); + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GE(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request_.start); + EXPECT_EQ(result.waypoints.back(), request_.goal); + for (std::size_t i = 1; i < result.waypoints.size(); ++i) { + for (int sample = 0; sample <= 100; ++sample) { + std::vector q(7); + for (std::size_t joint = 0; joint < 7; ++joint) { + q[joint] = result.waypoints[i - 1][joint] + + (result.waypoints[i][joint] - result.waypoints[i - 1][joint]) * sample / 100.0; + } + EXPECT_TRUE(request_.is_state_valid(q)) << "Invalid edge " << i; + } + } +} + +TEST_F(RrtConnectSelfCollisionTest, RejectsKnownGen2CollisionPose) +{ + request_.goal = {-0.42656969579233, 1.41426471041774, -2.67949400419915, + 2.45814854129954, -2.35907388079205, 1.14125209449898, + 1.53232912981414}; + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(result.waypoints.empty()); +} + +class RrtConnectObstacleTest : public ::testing::Test { +protected: + void SetUp() override + { + char path[] = "/tmp/cmvr_rrt_obstacle_XXXXXX"; + const int fd = mkstemp(path); + ASSERT_GE(fd, 0); + close(fd); + urdf_path_ = path; + std::ofstream urdf(urdf_path_); + ASSERT_TRUE(urdf.is_open()); + // A planar test mechanism makes obstacle clearance independently + // checkable: its tool center is exactly (q[0], q[1], 0). + urdf << R"( + + + + + + + + + + + + + +)"; + urdf.close(); + ASSERT_TRUE(urdf.good()); + + BoxObstacle obstacle; + obstacle.name = "blocking_box"; + obstacle.frame_id = "base"; + obstacle.size_m = Eigen::Vector3d(0.35, 0.70, 0.20); + CollisionOptions options; + options.obstacles.push_back(obstacle); + std::string error; + ASSERT_TRUE(checker_.init(urdf_path_, {"x", "y"}, options, &error)) << error; + ASSERT_EQ(checker_.activePairCount(), 1U); + + request_.start = {-0.8, 0.0}; + request_.goal = {0.8, 0.0}; + request_.lower_bounds = {-1.0, -1.0}; + request_.upper_bounds = {1.0, 1.0}; + request_.is_state_valid = [&](const auto& q) { + const auto result = checker_.check(q); + // Preserve 5 mm beyond the required clearance to account for + // finite motion-validation spacing at the obstacle corners. + return result.valid && !result.in_collision && + result.minimum_distance_m > kClearanceM + 0.005; + }; + cfg_.set_algorithm(config::RRT_CONNECT); + cfg_.mutable_rrt_connect()->set_timeout_s(2.0); + cfg_.mutable_rrt_connect()->set_range_rad(0.2); + cfg_.mutable_rrt_connect()->set_collision_check_step_rad(0.001); + } + + void TearDown() override + { + if (!urdf_path_.empty()) { + std::remove(urdf_path_.c_str()); + } + } + + static constexpr double kClearanceM = 0.02; + std::string urdf_path_; + CollisionChecker checker_; + JointPathRequest request_; + config::JointPathConfig cfg_; +}; + +TEST_F(RrtConnectObstacleTest, PlansAroundBoxAndKeepsClearanceAfterShortcut) +{ + ASSERT_TRUE(request_.is_state_valid(request_.start)); + ASSERT_TRUE(request_.is_state_valid(request_.goal)); + const auto blocked = checker_.check(std::vector{0.0, 0.0}); + ASSERT_TRUE(blocked.valid) << blocked.error; + ASSERT_TRUE(blocked.in_collision); // The direct start-to-goal segment is blocked. + + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); // Includes ropeShortcutPath. + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GT(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request_.start); + EXPECT_EQ(result.waypoints.back(), request_.goal); + + for (std::size_t edge = 1; edge < result.waypoints.size(); ++edge) { + const auto& a = result.waypoints[edge - 1]; + const auto& b = result.waypoints[edge]; + const double extent = std::max(std::abs(b[0] - a[0]), std::abs(b[1] - a[1])); + const int samples = std::max(1, static_cast(std::ceil(extent / 0.0005))); + for (int sample = 0; sample <= samples; ++sample) { + const double ratio = static_cast(sample) / samples; + const std::vector q{a[0] + (b[0] - a[0]) * ratio, + a[1] + (b[1] - a[1]) * ratio}; + const auto collision = checker_.check(q); + ASSERT_TRUE(collision.valid) << collision.error; + ASSERT_FALSE(collision.in_collision) << "edge=" << edge << ", sample=" << sample; + EXPECT_GT(collision.minimum_distance_m, kClearanceM) + << "edge=" << edge << ", sample=" << sample; + // Independent axis-aligned box distance, without the checker. + const double dx = std::max(0.0, std::abs(q[0]) - 0.225); + const double dy = std::max(0.0, std::abs(q[1]) - 0.400); + EXPECT_GT(std::hypot(dx, dy), kClearanceM) + << "edge=" << edge << ", sample=" << sample; + } + } +} + +TEST_F(RrtConnectObstacleTest, RejectsStartAndGoalInsideObstacle) +{ + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + + request_.start = {0.0, 0.0}; + auto result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(result.waypoints.empty()); + + request_.start = {-0.8, 0.0}; + request_.goal = {0.0, 0.0}; + result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(result.waypoints.empty()); +} + +} // namespace +} // namespace cmvr + +int main(int argc, char** argv) +{ + ompl::RNG::setSeed(42); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp new file mode 100644 index 00000000..3a257642 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp @@ -0,0 +1,304 @@ +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "cmvr/config/arm_config/arm_config.pb.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { +namespace { + +config::JointPathConfig defaultRrtConnectConfig() +{ + config::JointPathConfig cfg; + cfg.set_algorithm(config::RRT_CONNECT); + return cfg; +} + +JointPathRequest freeSpaceRequest(std::size_t dof = 7) +{ + JointPathRequest request; + request.start.assign(dof, -0.7); + request.goal.assign(dof, 0.7); + request.lower_bounds.assign(dof, -1.0); + request.upper_bounds.assign(dof, 1.0); + request.is_state_valid = [](const auto&) { return true; }; + return request; +} + +void expectValidPath(const JointPathResult& result, const JointPathRequest& request) +{ + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GE(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request.start); + EXPECT_EQ(result.waypoints.back(), request.goal); + for (std::size_t i = 1; i < result.waypoints.size(); ++i) { + const auto& a = result.waypoints[i - 1]; + const auto& b = result.waypoints[i]; + ASSERT_EQ(a.size(), request.start.size()); + ASSERT_EQ(b.size(), request.start.size()); + double distance = 0.0; + for (std::size_t joint = 0; joint < a.size(); ++joint) { + distance = std::max(distance, std::abs(b[joint] - a[joint])); + } + const auto count = static_cast(std::ceil(distance / 0.002)) + 1; + for (std::size_t sample = 0; sample <= count; ++sample) { + std::vector q(a.size()); + for (std::size_t joint = 0; joint < q.size(); ++joint) { + q[joint] = a[joint] + (b[joint] - a[joint]) * sample / count; + EXPECT_GE(q[joint], request.lower_bounds[joint]); + EXPECT_LE(q[joint], request.upper_bounds[joint]); + } + ASSERT_TRUE(request.is_state_valid(q)) << "Invalid interior of edge " << i; + } + } +} + +TEST(RrtConnectTest, PlansBoundedSevenJointPath) +{ + const auto request = freeSpaceRequest(); + const std::shared_ptr planner = + JointPathPlannerFactory::create(defaultRrtConnectConfig()); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + expectValidPath(result, request); + EXPECT_GT(result.validity_checks, 2U); +} + +TEST(RrtConnectTest, RoutesAroundBlockedDirectConnection) +{ + auto request = freeSpaceRequest(2); + request.start = {-0.8, 0.0}; + request.goal = {0.8, 0.0}; + request.is_state_valid = [](const auto& q) { + return std::abs(q[0]) >= 0.2 || std::abs(q[1]) >= 0.5; + }; + ASSERT_FALSE(request.is_state_valid({0.0, 0.0})); + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(2.0); + cfg.mutable_rrt_connect()->set_collision_check_step_rad(0.005); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + expectValidPath(planner->plan(request), request); +} + +TEST(RrtConnectTest, RejectsBlockedEdgesEvenWithValidEndpoints) +{ + auto request = freeSpaceRequest(1); + request.is_state_valid = [](const auto& q) { return std::abs(q[0]) >= 0.05; }; + ASSERT_TRUE(request.is_state_valid(request.start)); + ASSERT_TRUE(request.is_state_valid(request.goal)); + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(0.03); + cfg.mutable_rrt_connect()->set_range_rad(2.0); + cfg.mutable_rrt_connect()->set_collision_check_step_rad(0.01); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::TimedOut); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(RrtConnectTest, RequiresExplicitValidityChecker) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = {}; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, RejectsMalformedJointVectorsAndBounds) +{ + RrtConnect planner; + auto request = freeSpaceRequest(); + request.goal.pop_back(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.upper_bounds[0] = request.lower_bounds[0]; + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.start[0] = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.upper_bounds[0] = std::numeric_limits::infinity(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + EXPECT_EQ(planner.plan(freeSpaceRequest(0)).status, JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, RejectsInvalidOptions) +{ + const auto request = freeSpaceRequest(); + for (double value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + for (int field = 0; field < 3; ++field) { + RrtConnectOptions options; + auto cfg = defaultRrtConnectConfig(); + if (field == 0) { + options.timeout_s = value; + cfg.mutable_rrt_connect()->set_timeout_s(value); + } + if (field == 1) { + options.range_rad = value; + cfg.mutable_rrt_connect()->set_range_rad(value); + } + if (field == 2) { + options.collision_check_step_rad = value; + cfg.mutable_rrt_connect()->set_collision_check_step_rad(value); + } + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + EXPECT_EQ(RrtConnect{options}.plan(request).status, + JointPathStatus::InvalidRequest); + } + } + RrtConnectOptions options; + options.collision_check_step_rad = 1e-12; + EXPECT_EQ(RrtConnect{options}.plan(request).status, + JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, DoesNotClampOutOfBoundsEndpoints) +{ + auto request = freeSpaceRequest(); + request.start[0] = -1.1; + const auto start = RrtConnect{}.plan(request); + EXPECT_EQ(start.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(start.waypoints.empty()); + request = freeSpaceRequest(); + request.goal[0] = 1.1; + const auto goal = RrtConnect{}.plan(request); + EXPECT_EQ(goal.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(goal.waypoints.empty()); +} + +TEST(RrtConnectTest, RejectsCollidingEndpoints) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = [](const auto& q) { return q[0] > 0.0; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidStart); + request.is_state_valid = [](const auto& q) { return q[0] < 0.0; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidGoal); +} + +TEST(RrtConnectTest, ReturnsSingleStateForUnchangedValidGoal) +{ + auto request = freeSpaceRequest(); + request.goal = request.start; + const auto result = RrtConnect{}.plan(request); + ASSERT_TRUE(result.ok()) << result.message; + EXPECT_EQ(result.waypoints, JointPath{request.start}); + request.is_state_valid = [](const auto&) { return false; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidStart); +} + +TEST(RrtConnectTest, SupportsCancellationBeforeAndDuringSearch) +{ + auto request = freeSpaceRequest(); + request.is_cancelled = [] { return true; }; + const auto before = RrtConnect{}.plan(request); + EXPECT_EQ(before.status, JointPathStatus::Cancelled); + EXPECT_EQ(before.validity_checks, 0U); + EXPECT_TRUE(before.waypoints.empty()); + std::size_t checks = 0; + request.is_state_valid = [&](const auto&) { ++checks; return true; }; + request.is_cancelled = [&] { return checks >= 20; }; + const auto during = RrtConnect{}.plan(request); + EXPECT_EQ(during.status, JointPathStatus::Cancelled); + EXPECT_TRUE(during.waypoints.empty()); +} + +TEST(RrtConnectTest, ContainsCallbackExceptionsDuringSearch) +{ + auto request = freeSpaceRequest(); + int checks = 0; + request.is_state_valid = [&](const auto&) { + if (++checks == 10) throw std::runtime_error("collision backend unavailable"); + return true; + }; + const auto result = RrtConnect{}.plan(request); + EXPECT_EQ(result.status, JointPathStatus::ValidationError); + EXPECT_TRUE(result.waypoints.empty()); + EXPECT_NE(result.message.find("collision backend unavailable"), std::string::npos); + request.is_cancelled = []() -> bool { throw std::runtime_error("cancel failure"); }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::ValidationError); +} + +TEST(RrtConnectTest, IncludesValidationTimeInBudget) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = [](const auto&) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + return true; + }; + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(0.005); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::TimedOut); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(RrtConnectTest, DoesNotReusePreviousSolution) +{ + const auto planner = JointPathPlannerFactory::create(defaultRrtConnectConfig()); + ASSERT_NE(planner, nullptr); + auto request = freeSpaceRequest(); + ASSERT_TRUE(planner->plan(request).ok()); + request.is_state_valid = [](const auto&) { return false; }; + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(JointPathPlannerFactoryTest, RejectsMissingOrUnknownAlgorithm) +{ + config::JointPathConfig cfg; + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + cfg.mutable_rrt_connect(); + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + cfg.set_algorithm(static_cast(999)); + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); +} + +TEST(JointPathPlannerFactoryTest, LoadsArmConfigAndAppliesResolution) +{ + config::RobotArmConfig arm; + ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb( + motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 1.0 + range_rad: 0.05 + collision_check_step_rad: 0.001 + } + } + } + )pb", &arm)); + const auto planner = JointPathPlannerFactory::create(arm.motion().joint_path()); + ASSERT_NE(planner, nullptr); + const auto request = freeSpaceRequest(1); + const auto result = planner->plan(request); + expectValidPath(result, request); + // Covering the 1.4 rad path at 0.001 rad resolution needs at least 1400 + // checks. The default 0.02 rad resolution would not satisfy this bound. + EXPECT_GE(result.validity_checks, 1400U); +} + +} // namespace +} // namespace cmvr + +int main(int argc, char** argv) +{ + // Set once, before creating any OMPL RNG. Never change process-wide seeds + // inside the production planner. + ompl::RNG::setSeed(42); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/cmvr-es/algorithms/smoother/CMakeLists.txt b/cmvr-es/algorithms/smoother/CMakeLists.txt new file mode 100644 index 00000000..63e2faf5 --- /dev/null +++ b/cmvr-es/algorithms/smoother/CMakeLists.txt @@ -0,0 +1,11 @@ +add_library(joint_trajectory_smoother SHARED + bspline/src/bspline_smoother.cpp) +target_include_directories(joint_trajectory_smoother PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(joint_trajectory_smoother PUBLIC cmvr_es::curves cmvr_es::proto) +add_library(cmvr_es::joint_trajectory_smoother ALIAS joint_trajectory_smoother) +install(TARGETS joint_trajectory_smoother LIBRARY DESTINATION lib) + +add_executable(bspline_smoother_test + bspline/test/bspline_smoother_test.cpp) +target_link_libraries(bspline_smoother_test PRIVATE + cmvr_es::joint_trajectory_smoother gtest gtest_main) diff --git a/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h b/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h new file mode 100644 index 00000000..ed2b0db1 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h @@ -0,0 +1,23 @@ +#pragma once + +#include "algorithms/smoother/joint_trajectory_smoother.h" + +namespace cmvr::device { + +class BSplineSmoother final : public JointTrajectorySmoother { +public: + explicit BSplineSmoother(double control_point_spacing_rad = 0.05); + + bool init() override; + + bool smooth(const std::vector>& waypoints, + const MotionOptions& limits, + double sample_period_s, + JointTrajectory& output) const override; + +private: + double control_point_spacing_rad_; + bool initialized_{false}; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp b/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp new file mode 100644 index 00000000..8b6833a1 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp @@ -0,0 +1,128 @@ +#include "algorithms/smoother/bspline/include/bspline_smoother.h" + +#include +#include +#include +#include + +#include "curves/bspline/include/quintic_bspline.h" +#include "common/base/logging/logger.h" + +namespace cmvr::device { + +BSplineSmoother::BSplineSmoother(const double control_point_spacing_rad) + : control_point_spacing_rad_(control_point_spacing_rad) +{ +} + +bool BSplineSmoother::init() +{ + initialized_ = std::isfinite(control_point_spacing_rad_) && control_point_spacing_rad_ > 0.0; + return initialized_; +} + +bool BSplineSmoother::smooth( + const std::vector>& waypoints, + const MotionOptions& limits, + const double sample_period_s, + JointTrajectory& output) const +{ + output.clear(); + const auto begin = std::chrono::steady_clock::now(); + if (!initialized_ || waypoints.size() < 2 || waypoints.front().empty() || + !std::isfinite(limits.velocity) || limits.velocity <= 0.0 || + !std::isfinite(limits.acceleration) || limits.acceleration <= 0.0 || + !std::isfinite(limits.jerk) || limits.jerk <= 0.0 || + !std::isfinite(sample_period_s) || sample_period_s <= 0.0) { + CMVR_LOG(ERROR) << "[BSplineSmoother] invalid path or motion limits"; + return false; + } + const auto dof = waypoints.front().size(); + if (!limits.joint_velocity_limits.empty() && limits.joint_velocity_limits.size() != dof) { + CMVR_LOG(ERROR) << "[BSplineSmoother] joint velocity limit count does not match DOF"; + return false; + } + + try { + std::vector velocity_limits(dof, limits.velocity); + for (std::size_t j = 0; j < limits.joint_velocity_limits.size(); ++j) { + const double limit = limits.joint_velocity_limits[j]; + if (!std::isfinite(limit) || limit <= 0.0) return false; + velocity_limits[j] = std::min(limits.velocity, limit); + } + const auto spline = QuinticBSpline::create( + waypoints, velocity_limits, std::vector(dof, limits.acceleration), + std::vector(dof, limits.jerk), sample_period_s, + limits.cancellation_requested, control_point_spacing_rad_); + const double duration = spline->timeInterval()[1]; + const double count = std::ceil(duration / sample_period_s); + if (!std::isfinite(count) || count < 1.0 || count > 1000000) { + CMVR_LOG(ERROR) << "[BSplineSmoother] sampling exceeds one million intervals"; + return false; + } + + // Derivative-control convex hulls bound the entire curve, not just its samples. + const auto v_bounds = spline->derivativeBounds(1); + const auto a_bounds = spline->derivativeBounds(2); + const auto j_bounds = spline->derivativeBounds(3); + if (!v_bounds.allFinite() || !a_bounds.allFinite() || !j_bounds.allFinite()) return false; + double v_utilization = 0.0, a_utilization = 0.0, j_utilization = 0.0; + for (std::size_t j = 0; j < dof; ++j) { + v_utilization = std::max(v_utilization, v_bounds[j] / velocity_limits[j]); + a_utilization = std::max(a_utilization, a_bounds[j] / limits.acceleration); + j_utilization = std::max(j_utilization, j_bounds[j] / limits.jerk); + } + if (v_utilization > 1.0 + 1e-6 || a_utilization > 1.0 + 1e-6 || + j_utilization > 1.0 + 1e-6) { + CMVR_LOG(ERROR) << "[BSplineSmoother] derivative bounds exceed motion limits"; + return false; + } + + JointTrajectory samples; + samples.reserve(static_cast(count) + 1); + const auto as_vector = [](const Eigen::VectorXd& value) { + return std::vector(value.data(), value.data() + value.size()); + }; + for (std::size_t i = 0; i <= static_cast(count); ++i) { + if (limits.cancellation_requested && limits.cancellation_requested()) return false; + JointTrajectoryPoint point; + point.time_s = i == static_cast(count) + ? duration : std::min(i * sample_period_s, duration); + point.position = as_vector(spline->q(point.time_s)); + point.velocity = as_vector(spline->qd(point.time_s)); + point.acceleration = as_vector(spline->qdd(point.time_s)); + point.jerk = as_vector(spline->qddd(point.time_s)); + for (std::size_t j = 0; j < dof; ++j) { + if (!std::isfinite(point.position[j]) || !std::isfinite(point.velocity[j]) || + !std::isfinite(point.acceleration[j]) || !std::isfinite(point.jerk[j]) || + std::abs(point.velocity[j]) > velocity_limits[j] + 1e-6 || + std::abs(point.acceleration[j]) > limits.acceleration + 1e-6 || + std::abs(point.jerk[j]) > limits.jerk + 1e-6) { + CMVR_LOG(ERROR) << "[BSplineSmoother] invalid sample: point=" + << i << ", joint=" << j; + return false; + } + } + samples.push_back(std::move(point)); + if (samples.back().time_s == duration) break; + } + output = std::move(samples); + CMVR_LOG(INFO) << "[BSplineSmoother] planning_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - begin).count() + << ", trajectory_time_s=" << duration + << ", path=quintic_bspline, control_points=" << spline->controlPoints().cols() + << ", v_bound_utilization=" << v_utilization + << ", a_bound_utilization=" << a_utilization + << ", j_bound_utilization=" << j_utilization; + return true; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[BSplineSmoother] " << e.what(); + return false; + } catch (...) { + CMVR_LOG(ERROR) << "[BSplineSmoother] planning callback failed"; + return false; + } +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp b/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp new file mode 100644 index 00000000..f5246884 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp @@ -0,0 +1,519 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "algorithms/smoother/bspline/include/bspline_smoother.h" +#include "algorithms/smoother/joint_trajectory_validation.h" +#include "curves/bspline/include/quintic_bspline.h" + +namespace cmvr::device { +namespace { + +constexpr std::size_t kDof = 7; + +JointTrajectory makeRecordedTrajectory(const std::size_t point_count) +{ + JointTrajectory trajectory; + trajectory.reserve(point_count); + for (std::size_t i = 0; i < point_count; ++i) { + const double s = static_cast(i) / + static_cast(point_count - 1); + JointTrajectoryPoint point; + point.time_s = static_cast(i) * 0.002; + point.position = { + 0.40 * s, + -0.25 * s + 0.03 * std::sin(3.141592653589793 * s), + 0.20 * s * s, + 0.30 * std::sin(1.5707963267948966 * s), + -0.12 * s, + 0.15 * s, + -0.08 * std::sin(3.141592653589793 * s), + }; + point.velocity.assign(kDof, 0.0); + trajectory.push_back(std::move(point)); + } + return trajectory; +} + +double maximumPositionError(const std::vector& lhs, + const std::vector& rhs) +{ + if (lhs.size() != rhs.size()) { + return std::numeric_limits::infinity(); + } + double maximum = 0.0; + for (std::size_t i = 0; i < lhs.size(); ++i) { + maximum = std::max(maximum, std::abs(lhs[i] - rhs[i])); + } + return maximum; +} + +void writeTrajectoryCsv(const char* name, const JointTrajectory& trajectory) +{ + const char* directory = std::getenv("CMVR_PATH_TEST_CSV_DIR"); + if (!directory || !*directory || trajectory.empty()) return; + std::error_code error; + std::filesystem::create_directories(directory, error); + ASSERT_FALSE(error) << error.message(); + std::ofstream output(std::filesystem::path(directory) / (std::string(name) + ".csv")); + ASSERT_TRUE(output.is_open()); + output << "time_s"; + for (std::size_t j = 0; j < trajectory.front().position.size(); ++j) { + output << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 + << "_rad_s2,j" << j + 1 << "_rad_s3"; + } + output << '\n' << std::setprecision(17); + for (const auto& point : trajectory) { + output << point.time_s; + for (std::size_t j = 0; j < point.position.size(); ++j) { + output << ',' << point.position[j] << ',' << point.velocity[j] + << ',' << point.acceleration[j] << ',' << point.jerk[j]; + } + output << '\n'; + } + ASSERT_TRUE(output.good()); +} + +void expectConsistentTrajectory(const JointTrajectory& trajectory, + const MotionOptions& options) +{ + ASSERT_GT(trajectory.size(), 2u); + const auto dof = trajectory.front().position.size(); + double jerk_error_squared = 0.0, maximum_jerk = 0.0; + std::size_t derivative_samples = 0; + for (std::size_t i = 0; i < trajectory.size(); ++i) { + const auto& point = trajectory[i]; + ASSERT_EQ(point.position.size(), dof); + ASSERT_EQ(point.velocity.size(), dof); + ASSERT_EQ(point.acceleration.size(), dof); + ASSERT_EQ(point.jerk.size(), dof); + ASSERT_TRUE(std::isfinite(point.time_s)); + for (std::size_t j = 0; j < dof; ++j) { + ASSERT_TRUE(std::isfinite(point.position[j])); + ASSERT_TRUE(std::isfinite(point.velocity[j])); + ASSERT_TRUE(std::isfinite(point.acceleration[j])); + ASSERT_TRUE(std::isfinite(point.jerk[j])); + const double velocity_limit = options.joint_velocity_limits.empty() + ? options.velocity : std::min(options.velocity, options.joint_velocity_limits[j]); + EXPECT_LE(std::abs(point.velocity[j]), velocity_limit + 1e-6); + EXPECT_LE(std::abs(point.acceleration[j]), options.acceleration + 1e-6); + EXPECT_LE(std::abs(point.jerk[j]), options.jerk + 1e-6); + maximum_jerk = std::max(maximum_jerk, std::abs(point.jerk[j])); + if (i == 0) continue; + const auto& previous = trajectory[i - 1]; + const double dt = point.time_s - previous.time_s; + ASSERT_GT(dt, 0.0); + // Check that the reported derivatives describe the executed positions. + EXPECT_NEAR(point.position[j] - previous.position[j], + 0.5 * (point.velocity[j] + previous.velocity[j]) * dt, + options.jerk * dt * dt * dt / 12.0 + 1e-9); + EXPECT_NEAR(point.velocity[j] - previous.velocity[j], + 0.5 * (point.acceleration[j] + previous.acceleration[j]) * dt, + options.jerk * dt * dt / 2.0 + 1e-9); + EXPECT_LE(std::abs(point.acceleration[j] - previous.acceleration[j]), + options.jerk * dt + 1e-7); + if (dt > 1e-9) { + const double error = (point.acceleration[j] - previous.acceleration[j]) / dt - + 0.5 * (point.jerk[j] + previous.jerk[j]); + jerk_error_squared += error * error; + ++derivative_samples; + } + } + } + // Compare analytic jerk with interval-average acceleration changes. + ASSERT_GT(derivative_samples, 0u); + EXPECT_LE(std::sqrt(jerk_error_squared / derivative_samples), 0.05 * maximum_jerk + 1e-6); + for (const auto* endpoint : {&trajectory.front(), &trajectory.back()}) { + for (const double velocity : endpoint->velocity) EXPECT_NEAR(velocity, 0.0, 1e-9); + for (const double acceleration : endpoint->acceleration) EXPECT_NEAR(acceleration, 0.0, 1e-8); + } +} + +TEST(BSplineSmootherTest, PreservesLineWithAnalyticLimitsAndJerkScaling) +{ + BSplineSmoother smoother(0.05); + ASSERT_TRUE(smoother.init()); + const auto& initialized = smoother; + const std::vector start{0.12, -0.2, 0.4, 0.15}; + const std::vector target{0.42, -0.35, 0.475, 0.15}; + MotionOptions options; + options.velocity = 0.6; + options.acceleration = 1.2; + options.joint_velocity_limits = {0.4, 0.2, 0.12, 0.3}; + double normal_duration = 0.0; + for (int scenario = 0; scenario < 3; ++scenario) { + SCOPED_TRACE(scenario); + options.jerk = scenario == 1 ? 0.1 : 100.0; + const double scaling = scenario == 2 ? 0.5 : 1.0; + JointTrajectory trajectory; + MotionOptions effective_limits = options; + effective_limits.velocity *= scaling; + for (auto& limit : effective_limits.joint_velocity_limits) limit *= scaling; + ASSERT_TRUE(initialized.smooth({start, target}, effective_limits, 0.001, trajectory)); + ASSERT_GT(trajectory.size(), 2u); + expectConsistentTrajectory(trajectory, effective_limits); + const char* names[]{"smooth_line", "smooth_line_low_jerk", "smooth_line_scaled_limits"}; + writeTrajectoryCsv(names[scenario], trajectory); + EXPECT_LT(maximumPositionError(trajectory.front().position, start), 1e-12); + EXPECT_LT(maximumPositionError(trajectory.back().position, target), 1e-12); + if (scenario == 0) normal_duration = trajectory.back().time_s; + else EXPECT_GT(trajectory.back().time_s, normal_duration); + + double previous_progress = 0.0; + int previous_sign = 0, acceleration_reversals = 0; + for (const auto& point : trajectory) { + const double progress = (point.position[0] - start[0]) / + (target[0] - start[0]); + EXPECT_GE(progress, previous_progress - 1e-12); + EXPECT_GE(progress, -1e-12); + EXPECT_LE(progress, 1.0 + 1e-12); + previous_progress = progress; + for (std::size_t j = 0; j < start.size(); ++j) { + EXPECT_NEAR(point.position[j], start[j] + + progress * (target[j] - start[j]), 1e-12); + EXPECT_GE(point.position[j], std::min(start[j], target[j]) - 1e-12); + EXPECT_LE(point.position[j], std::max(start[j], target[j]) + 1e-12); + } + // Rest-to-rest motion on one joint-space line needs one acceleration reversal. + if (std::abs(point.acceleration[0]) > 1e-7) { + const int sign = point.acceleration[0] > 0.0 ? 1 : -1; + if (previous_sign && previous_sign != sign) ++acceleration_reversals; + previous_sign = sign; + } + EXPECT_NEAR(point.velocity.back(), 0.0, 1e-12); + EXPECT_NEAR(point.acceleration.back(), 0.0, 1e-12); + EXPECT_NEAR(point.jerk.back(), 0.0, 1e-12); + } + EXPECT_EQ(acceleration_reversals, 1); + } +} + +TEST(BSplineSmootherTest, RejectsInvalidInputsAndHonorsCancellation) +{ + BSplineSmoother smoother(0.05); + ASSERT_TRUE(smoother.init()); + const std::vector> path{{0.0, 0.0}, {0.3, -0.1}}; + MotionOptions options; + options.velocity = 0.4; + options.acceleration = 0.8; + options.jerk = 30.0; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + JointTrajectory trajectory; + const auto reject = [&](const std::vector>& waypoints, + const MotionOptions& limits, const double period = 0.001) { + trajectory.resize(1); + EXPECT_FALSE(smoother.smooth(waypoints, limits, period, trajectory)); + EXPECT_TRUE(trajectory.empty()); + }; + reject({}, options); + reject({path.front()}, options); + reject({{}, {}}, options); + reject({path.front(), {0.3}}, options); + for (const double invalid : {nan, inf}) { + reject({{invalid, 0.0}, path.back()}, options); + reject({path.front(), {0.3, invalid}}, options); + } + for (const double invalid : {0.0, -1.0, nan, inf}) { + SCOPED_TRACE(invalid); + for (int field = 0; field < 3; ++field) { + MotionOptions bad = options; + if (field == 0) bad.velocity = invalid; + if (field == 1) bad.acceleration = invalid; + if (field == 2) bad.jerk = invalid; + reject(path, bad); + } + reject(path, options, invalid); + BSplineSmoother bad_spacing(invalid); + EXPECT_FALSE(bad_spacing.init()); + } + for (const auto& invalid : std::vector>{ + {1.0}, {1.0, 0.0}, {1.0, -1.0}, {nan, 1.0}, {inf, 1.0}}) { + MotionOptions bad = options; + bad.joint_velocity_limits = invalid; + reject(path, bad); + } + options.cancellation_requested = [] { return true; }; + reject(path, options); +} + +TEST(JointTrajectoryValidationTest, RejectsInvalidOutputTrajectory) +{ + MotionOptions options; + options.velocity = 0.15; + options.acceleration = 5.0; + + JointTrajectory trajectory = makeRecordedTrajectory(10); + trajectory[5].velocity[2] = options.velocity + 0.01; + EXPECT_FALSE(validateJointTrajectory(trajectory, kDof, options)); + + trajectory[5].velocity[2] = 0.0; + trajectory[5].time_s = trajectory[4].time_s; + EXPECT_FALSE(validateJointTrajectory(trajectory, kDof, options)); +} + +void writeBSplineCsv(const char* name, const cmvr::QuinticBSpline& spline) +{ + if (!std::getenv("CMVR_PATH_TEST_CSV_DIR")) return; + const double duration = spline.timeInterval()[1]; + const auto count = static_cast(std::ceil(duration / 0.001)); + JointTrajectory samples; + samples.reserve(count + 1); + for (std::size_t i = 0; i <= count; ++i) { + JointTrajectoryPoint point; + point.time_s = duration * static_cast(i) / static_cast(count); + const auto q = spline.q(point.time_s), v = spline.qd(point.time_s); + const auto a = spline.qdd(point.time_s), j = spline.qddd(point.time_s); + point.position.assign(q.data(), q.data() + q.size()); + point.velocity.assign(v.data(), v.data() + v.size()); + point.acceleration.assign(a.data(), a.data() + a.size()); + point.jerk.assign(j.data(), j.data() + j.size()); + samples.push_back(std::move(point)); + } + writeTrajectoryCsv(name, samples); +} + +TEST(QuinticBSplineTest, AnalyticDerivativesAndJointLimits) +{ + const std::vector>> paths{ + {{0.0, 0.0, 0.0}, {0.3, -0.15, 0.075}}, + {{0.0, 0.0, 0.0}, {0.025, 0.006, -0.003}, + {0.35, 0.18, -0.07}, {0.8, 0.05, 0.1}}}; + const std::vector velocity{0.3, 0.15, 0.08}; + const std::vector acceleration{0.8, 0.5, 0.3}; + const std::vector jerk{30.0, 8.0, 2.0}; + for (std::size_t scenario = 0; scenario < paths.size(); ++scenario) { + SCOPED_TRACE(scenario); + const auto curve = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, jerk, 0.01); + ASSERT_TRUE(curve); + const double duration = curve->timeInterval()[1]; + ASSERT_TRUE(std::isfinite(duration)); + ASSERT_GT(duration, 0.0); + EXPECT_DOUBLE_EQ(curve->timeInterval()[0], 0.0); + for (const double time : {0.0, duration}) { + const auto& endpoint = time == 0.0 ? paths[scenario].front() : paths[scenario].back(); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_NEAR(curve->q(time)[axis], endpoint[axis], 1e-12); + EXPECT_NEAR(curve->qd(time)[axis], 0.0, 1e-12); + EXPECT_NEAR(curve->qdd(time)[axis], 0.0, 1e-12); + } + } + const auto vb = curve->derivativeBounds(1), ab = curve->derivativeBounds(2); + const auto jb = curve->derivativeBounds(3); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_LE(vb[axis], velocity[axis] + 1e-12); + EXPECT_LE(ab[axis], acceleration[axis] + 1e-12); + EXPECT_LE(jb[axis], jerk[axis] + 1e-12); + } + for (int sample = 0; sample <= 2000; ++sample) { + const double time = duration * sample / 2000.0; + EXPECT_TRUE(curve->q(time).allFinite()); + EXPECT_TRUE((curve->qd(time).cwiseAbs().array() <= vb.array() + 1e-10).all()); + EXPECT_TRUE((curve->qdd(time).cwiseAbs().array() <= ab.array() + 1e-10).all()); + EXPECT_TRUE((curve->qddd(time).cwiseAbs().array() <= jb.array() + 1e-10).all()); + } + // Differentiate the evaluated curves, independently of their stored derivative controls. + const double h = duration * 1e-6; + for (int sample = 1; sample < 100; ++sample) { + const double time = duration * sample / 100.0; + EXPECT_LT(((curve->q(time + h) - curve->q(time - h)) / (2 * h) - + curve->qd(time)).cwiseAbs().maxCoeff(), 2e-6); + EXPECT_LT(((curve->qd(time + h) - curve->qd(time - h)) / (2 * h) - + curve->qdd(time)).cwiseAbs().maxCoeff(), 2e-6); + EXPECT_LT(((curve->qdd(time + h) - curve->qdd(time - h)) / (2 * h) - + curve->qddd(time)).cwiseAbs().maxCoeff(), 2e-5); + } + const auto knots = curve->knotTimes(); + ASSERT_GE(knots.size(), 2u); + for (std::size_t k = 1; k + 1 < knots.size(); ++k) { + const double epsilon = 1e-7 * std::min(knots[k] - knots[k - 1], knots[k + 1] - knots[k]); + ASSERT_GT(epsilon, 0.0); + EXPECT_LT((curve->qddd(knots[k] + epsilon) - + curve->qddd(knots[k] - epsilon)).cwiseAbs().maxCoeff(), + 1e-4 * std::max(1.0, jb.maxCoeff())); + } + writeBSplineCsv(scenario == 0 ? "bspline_two_waypoint" : "bspline_uneven_waypoint", *curve); + } +} + +TEST(QuinticBSplineTest, UnevenCollinearWaypointsDoNotIntroduceSpeedRipple) +{ + const std::vector start{0.12, -0.2, 0.4}, delta{0.8, -0.4, 0.2}; + std::vector> waypoints; + for (const double progress : {0.0, 0.002, 0.03, 0.4, 0.83, 1.0}) { + std::vector point = start; + for (int axis = 0; axis < 3; ++axis) point[axis] += progress * delta[axis]; + waypoints.push_back(std::move(point)); + } + const auto curve = cmvr::QuinticBSpline::create( + waypoints, {0.4, 0.3, 0.2}, {0.8, 0.6, 0.4}, {30.0, 20.0, 10.0}, 0.01); + const auto reference = cmvr::QuinticBSpline::create( + {waypoints.front(), waypoints.back()}, {0.4, 0.3, 0.2}, + {0.8, 0.6, 0.4}, {30.0, 20.0, 10.0}, 0.01); + const double duration = curve->timeInterval()[1]; + EXPECT_NEAR(duration, reference->timeInterval()[1], 1e-10); + int acceleration_sign = 0, acceleration_reversals = 0; + const double threshold = 1e-5 * curve->derivativeBounds(2)[0]; + for (int sample = 0; sample <= 2000; ++sample) { + const double u = sample / 2000.0, time = duration * u; + const auto q = curve->q(time), v = curve->qd(time), a = curve->qdd(time); + EXPECT_LT((q - reference->q(time)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((v - reference->qd(time)).cwiseAbs().maxCoeff(), 1e-9); + EXPECT_GE(v[0], -1e-12); + if (sample > 40 && sample < 1960) EXPECT_GT(v[0], 1e-6); + // A straight path has the independent closed-form rest-to-rest quintic solution. + const double progress = u * u * u * (10.0 - 15.0 * u + 6.0 * u * u); + const double speed = 30.0 * u * u * (1.0 - u) * (1.0 - u) / duration; + const double accel = 60.0 * u * (1.0 - u) * (1.0 - 2.0 * u) / (duration * duration); + const double jerk = (60.0 - 360.0 * u + 360.0 * u * u) / (duration * duration * duration); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_NEAR(q[axis], start[axis] + delta[axis] * progress, 1e-10); + EXPECT_NEAR(v[axis], delta[axis] * speed, 1e-9); + EXPECT_NEAR(a[axis], delta[axis] * accel, 1e-8); + EXPECT_NEAR(curve->qddd(time)[axis], delta[axis] * jerk, 1e-7); + } + for (int axis = 1; axis < 3; ++axis) { + EXPECT_NEAR((q[axis] - start[axis]) * delta[0], (q[0] - start[0]) * delta[axis], 1e-12); + EXPECT_NEAR(v[axis] * delta[0], v[0] * delta[axis], 1e-12); + } + if (std::abs(a[0]) > threshold) { + const int sign = a[0] > 0.0 ? 1 : -1; + if (acceleration_sign != 0 && sign != acceleration_sign) ++acceleration_reversals; + acceleration_sign = sign; + } + } + EXPECT_EQ(acceleration_reversals, 1); + writeBSplineCsv("bspline_six_waypoint", *curve); +} + +TEST(QuinticBSplineTest, UniformTimeStretchScalesAllDerivatives) +{ + const std::vector> path{{0.0, 0.0}, {0.25, 0.3}, {0.7, -0.1}}; + const auto normal = cmvr::QuinticBSpline::create( + path, {0.4, 0.2}, {0.8, 0.6}, {30.0, 5.0}, 0.01); + const double normal_duration = normal->timeInterval()[1]; + const auto slow = cmvr::QuinticBSpline::create( + path, {0.4, 0.2}, {0.8, 0.6}, {30.0, 5.0}, 2 * normal_duration); + const double slow_duration = slow->timeInterval()[1]; + const double ratio = slow_duration / normal_duration; + EXPECT_GE(ratio, 2.0 - 1e-12); + for (int sample = 0; sample <= 100; ++sample) { + const double t = normal_duration * sample / 100.0, ts = slow_duration * sample / 100.0; + EXPECT_LT((normal->q(t) - slow->q(ts)).cwiseAbs().maxCoeff(), 1e-12); + EXPECT_LT((normal->qd(t) - ratio * slow->qd(ts)).cwiseAbs().maxCoeff(), 1e-11); + EXPECT_LT((normal->qdd(t) - ratio * ratio * slow->qdd(ts)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((normal->qddd(t) - ratio * ratio * ratio * slow->qddd(ts)).cwiseAbs().maxCoeff(), 1e-9); + } +} + +TEST(QuinticBSplineTest, JerkSweepPreservesGeometryAndLimits) +{ + std::vector> line; + for (const double progress : {0.0, 0.002, 0.03, 0.4, 0.83, 1.0}) { + line.push_back({0.12 + 0.8 * progress, -0.2 - 0.4 * progress, + 0.4 + 0.2 * progress}); + } + const std::vector>> paths{ + line, + {{0.0, 0.0, 0.0}, {0.025, 0.006, -0.003}, + {0.35, 0.18, -0.07}, {0.8, 0.05, 0.1}}}; + const std::vector velocity(3, 0.65), acceleration(3, 1.7); + for (std::size_t scenario = 0; scenario < paths.size(); ++scenario) { + SCOPED_TRACE(scenario); + const auto reference = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, std::vector(3, 100.0), 0.01); + const double reference_duration = reference->timeInterval()[1]; + double previous_duration = std::numeric_limits::infinity(); + for (const int jerk_limit : {1, 5, 30, 100}) { + SCOPED_TRACE(jerk_limit); + const auto curve = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, + std::vector(3, jerk_limit), 0.01); + const double duration = curve->timeInterval()[1]; + EXPECT_LE(duration, previous_duration + 1e-12); + if (jerk_limit == 1) EXPECT_GT(duration, reference_duration); + previous_duration = duration; + EXPECT_LE(curve->derivativeBounds(1).maxCoeff(), 0.65 + 1e-12); + EXPECT_LE(curve->derivativeBounds(2).maxCoeff(), 1.7 + 1e-12); + EXPECT_LE(curve->derivativeBounds(3).maxCoeff(), jerk_limit + 1e-12); + // Changing the jerk constraint stretches time; it must not alter + // the geometric curve or its normalized analytic derivatives. + const double ratio = duration / reference_duration; + for (int sample = 0; sample <= 100; ++sample) { + const double progress = sample / 100.0; + const double t = duration * progress, tr = reference_duration * progress; + EXPECT_LT((curve->q(t) - reference->q(tr)).cwiseAbs().maxCoeff(), 1e-12); + EXPECT_LT((ratio * curve->qd(t) - reference->qd(tr)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((ratio * ratio * curve->qdd(t) - reference->qdd(tr)).cwiseAbs().maxCoeff(), 1e-9); + EXPECT_LT((ratio * ratio * ratio * curve->qddd(t) - reference->qddd(tr)).cwiseAbs().maxCoeff(), 1e-8); + } + const std::string name = std::string(scenario == 0 ? "bspline_line_j" : "bspline_bent_j") + + (jerk_limit < 10 ? "00" : jerk_limit < 100 ? "0" : "") + std::to_string(jerk_limit); + writeBSplineCsv(name.c_str(), *curve); + } + } +} + +TEST(QuinticBSplineTest, DuplicateAndStationaryWaypoints) +{ + const std::vector> path{{0.1, -0.2}, {0.3, 0.1}, {0.5, 0.0}}; + const auto clean = cmvr::QuinticBSpline::create(path, {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.01); + const auto duplicates = cmvr::QuinticBSpline::create( + {path[0], path[0], path[1], path[1], path[2], path[2]}, + {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.01); + EXPECT_NEAR(clean->timeInterval()[1], duplicates->timeInterval()[1], 1e-12); + for (int i = 0; i <= 100; ++i) { + const double time = clean->timeInterval()[1] * i / 100.0; + EXPECT_LT((clean->q(time) - duplicates->q(time)).cwiseAbs().maxCoeff(), 1e-12); + } + const auto stationary = cmvr::QuinticBSpline::create( + {path[0], path[0], path[0]}, {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.125); + EXPECT_DOUBLE_EQ(stationary->timeInterval()[1], 0.125); + for (const double time : {0.0, 0.06, 0.125}) { + EXPECT_NEAR(stationary->q(time)[0], 0.1, 1e-14); + EXPECT_NEAR(stationary->q(time)[1], -0.2, 1e-14); + EXPECT_DOUBLE_EQ(stationary->qd(time).norm(), 0.0); + EXPECT_DOUBLE_EQ(stationary->qdd(time).norm(), 0.0); + EXPECT_DOUBLE_EQ(stationary->qddd(time).norm(), 0.0); + } +} + +TEST(QuinticBSplineTest, RejectsInvalidInputsAndHonorsCancellation) +{ + using Spline = cmvr::QuinticBSpline; + const std::vector> path{{0.0, 0.0}, {0.2, -0.1}}; + const std::vector limits{1.0, 1.0}; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + EXPECT_THROW(Spline::create({}, limits, limits, limits, 0.01), std::invalid_argument); + EXPECT_THROW(Spline::create({{}, {}}, {}, {}, {}, 0.01), std::invalid_argument); + EXPECT_THROW(Spline::create({{0.0, 0.0}, {0.2}}, limits, limits, limits, 0.01), std::invalid_argument); + for (const double invalid : {nan, inf}) { + EXPECT_THROW(Spline::create({{0.0, 0.0}, {invalid, 0.1}}, limits, limits, limits, 0.01), std::invalid_argument); + } + for (int order = 0; order < 3; ++order) { + for (const auto& invalid : std::vector>{{1.0}, {1.0, 0.0}, {1.0, -1.0}, {nan, 1.0}, {inf, 1.0}}) { + SCOPED_TRACE(order); + EXPECT_THROW(Spline::create(path, order == 0 ? invalid : limits, + order == 1 ? invalid : limits, order == 2 ? invalid : limits, 0.01), std::invalid_argument); + } + } + for (const double invalid : {0.0, -0.1, nan, inf}) { + EXPECT_THROW(Spline::create(path, limits, limits, limits, invalid), std::invalid_argument); + } + EXPECT_THROW(Spline::create(path, limits, limits, limits, 0.01, [] { return true; }), std::runtime_error); +} + +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h b/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h new file mode 100644 index 00000000..3d8ebded --- /dev/null +++ b/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +class JointTrajectorySmoother { +public: + virtual ~JointTrajectorySmoother() = default; + + virtual bool init() = 0; + + // Generate a timed, rest-to-rest trajectory from a joint-space path. + // Limits already include the caller's speed scaling. Smoothing may change + // the geometric path; the caller must recheck joint bounds and collisions. + virtual bool smooth(const std::vector>& waypoints, + const MotionOptions& limits, + double sample_period_s, + JointTrajectory& output) const = 0; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h b/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h new file mode 100644 index 00000000..54b522a6 --- /dev/null +++ b/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include "algorithms/smoother/bspline/include/bspline_smoother.h" +#include "cmvr/config/joint_motion_config.pb.h" + +namespace cmvr::device { + +class JointTrajectorySmootherFactory { +public: + static std::shared_ptr create( + const config::JointTrajectorySmootherConfig& cfg) + { + if (!cfg.has_quintic_bspline()) { + return nullptr; + } + const auto& spline = cfg.quintic_bspline(); + auto smoother = std::make_shared( + spline.has_control_point_spacing_rad() ? spline.control_point_spacing_rad() : 0.05); + if (!smoother->init()) { + return nullptr; + } + return smoother; + } +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/joint_trajectory_validation.h b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h new file mode 100644 index 00000000..f0dbffdc --- /dev/null +++ b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h @@ -0,0 +1,134 @@ +#pragma once + +#include +#include +#include + +#include "common/base/logging/logger.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +inline bool validateJointTrajectory( + const JointTrajectory& trajectory, + const std::size_t expected_dof, + const MotionOptions& limits) +{ + if (trajectory.size() < 2 || expected_dof == 0) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory must contain at least " + "two points and have a non-zero DOF"; + return false; + } + if (!std::isfinite(limits.velocity) || limits.velocity <= 0.0 || + !std::isfinite(limits.acceleration) || limits.acceleration <= 0.0) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity or acceleration limit is invalid"; + return false; + } + if (!limits.joint_velocity_limits.empty() && + limits.joint_velocity_limits.size() != expected_dof) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] joint velocity limit count does not match DOF"; + return false; + } + + constexpr double kVelocityTolerance = 1e-6; + constexpr double kAccelerationTolerance = 1e-3; + double maximum_velocity = 0.0; + double maximum_acceleration = 0.0; + double maximum_position_velocity = 0.0; + double maximum_position_acceleration = 0.0; + double maximum_jerk = 0.0; + std::vector previous_position_velocity(expected_dof, 0.0); + std::vector previous_acceleration(expected_dof, 0.0); + + for (std::size_t i = 0; i < trajectory.size(); ++i) { + const auto& point = trajectory[i]; + if (!std::isfinite(point.time_s) || + point.position.size() != expected_dof || + point.velocity.size() != expected_dof) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid trajectory point at index=" << i; + return false; + } + + double dt = 0.0; + if (i > 0) { + dt = point.time_s - trajectory[i - 1].time_s; + if (!std::isfinite(dt) || dt <= 0.0) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory time is not increasing at index=" + << i; + return false; + } + } + + for (std::size_t joint = 0; joint < expected_dof; ++joint) { + if (!std::isfinite(point.position[joint]) || + !std::isfinite(point.velocity[joint])) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] non-finite trajectory value at point=" + << i << ", joint=" << joint; + return false; + } + + const double velocity = std::abs(point.velocity[joint]); + const double velocity_limit = limits.joint_velocity_limits.empty() + ? limits.velocity + : limits.joint_velocity_limits[joint]; + if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid velocity limit for joint=" + << joint; + return false; + } + maximum_velocity = std::max(maximum_velocity, velocity); + if (velocity > velocity_limit + kVelocityTolerance) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity limit exceeded at point=" + << i << ", joint=" << joint + << ", actual=" << velocity + << ", limit=" << velocity_limit; + return false; + } + + if (i > 0) { + const double position_velocity = + (point.position[joint] - trajectory[i - 1].position[joint]) / dt; + const double acceleration = + (point.velocity[joint] - trajectory[i - 1].velocity[joint]) / dt; + maximum_position_velocity = std::max( + maximum_position_velocity, std::abs(position_velocity)); + maximum_acceleration = std::max( + maximum_acceleration, std::abs(acceleration)); + if (std::abs(acceleration) > + limits.acceleration + kAccelerationTolerance) { + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] acceleration limit exceeded at point=" + << i << ", joint=" << joint + << ", actual=" << std::abs(acceleration) + << ", limit=" << limits.acceleration; + return false; + } + if (i > 1) { + // Interval-average derivatives are located at interval midpoints. + const double midpoint_dt = 0.5 * (point.time_s - trajectory[i - 2].time_s); + maximum_position_acceleration = std::max( + maximum_position_acceleration, + std::abs(position_velocity - + previous_position_velocity[joint]) / midpoint_dt); + maximum_jerk = std::max( + maximum_jerk, + std::abs(acceleration - previous_acceleration[joint]) / midpoint_dt); + } + previous_position_velocity[joint] = position_velocity; + previous_acceleration[joint] = acceleration; + } + } + } + + CMVR_LOG(INFO) << "[JointTrajectoryValidation] trajectory validated" + << ", points=" << trajectory.size() + << ", max_velocity_rad_s=" << maximum_velocity + << ", max_discrete_acceleration_rad_s2=" << maximum_acceleration + << ", max_position_velocity_rad_s=" << maximum_position_velocity + << ", max_position_acceleration_rad_s2=" + << maximum_position_acceleration + << ", max_discrete_jerk_rad_s3=" << maximum_jerk; + return true; +} + + +} // namespace cmvr::device diff --git a/cmvr-es/common/math/qp_solver.h b/cmvr-es/common/math/qp_solver.h index d8d913fd..99494b4d 100644 --- a/cmvr-es/common/math/qp_solver.h +++ b/cmvr-es/common/math/qp_solver.h @@ -92,7 +92,9 @@ public: QPSolverImpl() = default; ~QPSolverImpl() = default; - void SetupImpl(int n_var, int n_const, double time_limit = 2e-3); + void SetupImpl(int n_var, int n_const, double time_limit = 2e-3, + double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3, + bool polish = false); void InitFunctionImpl(); void AddCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b); void SetCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b); @@ -135,13 +137,18 @@ private: Eigen::Matrix primal_variable_for_warmstart_; }; -inline void QPSolverImpl::SetupImpl(int n_var, int n_const, double time_limit) { +inline void QPSolverImpl::SetupImpl(int n_var, int n_const, double time_limit, + double absolute_tolerance, double relative_tolerance, + bool polish) { n_var_ = n_var; n_const_ = n_const; solver_.settings()->setWarmStart(true); solver_.settings()->setVerbosity(false); solver_.settings()->setTimeLimit(time_limit); + solver_.settings()->setAbsoluteTolerance(absolute_tolerance); + solver_.settings()->setRelativeTolerance(relative_tolerance); + solver_.settings()->setPolish(polish); solver_.data()->setNumberOfVariables(n_var_); solver_.data()->setNumberOfConstraints(n_const_); @@ -324,7 +331,9 @@ public: QPSolver(); ~QPSolver(); - void Setup(int n_var, int n_const, double time_limit = 2e-3); + void Setup(int n_var, int n_const, double time_limit = 2e-3, + double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3, + bool polish = false); void InitFunction(); @@ -363,8 +372,10 @@ inline QPSolver::QPSolver() { inline QPSolver::~QPSolver() = default; -inline void QPSolver::Setup(int n_var, int n_const, double time_limit) { - impl_->SetupImpl(n_var, n_const, time_limit); +inline void QPSolver::Setup(int n_var, int n_const, double time_limit, + double absolute_tolerance, double relative_tolerance, + bool polish) { + impl_->SetupImpl(n_var, n_const, time_limit, absolute_tolerance, relative_tolerance, polish); } inline void QPSolver::InitFunction() { diff --git a/cmvr-es/common/types/arm/arm_types.h b/cmvr-es/common/types/arm/arm_types.h index 12640271..fae83b05 100644 --- a/cmvr-es/common/types/arm/arm_types.h +++ b/cmvr-es/common/types/arm/arm_types.h @@ -7,7 +7,11 @@ #include #include +#include "environment/include/robot_model.h" + namespace cmvr::device { +using ::cmvr::JointLimit; +using ::cmvr::RobotModel; enum class ArmErrorCode { OK = 0, @@ -72,8 +76,8 @@ struct SpeedLOptions { // Requested linear jerk (m/s^3), capped by the arm's configured maximum. // Unset uses that maximum. std::optional linear_jerk; - // Unset follows the arm config. False preserves the original streaming - // direction-following policy used by PBVS; true enables fixed-axis reversal. + // Unset follows the arm config. True crosses zero on same-axis reversals; + // false stops first near a reversal. Direction changes are smoothed in 3D. std::optional continuous_linear_reversal; // Capture the first applied command's measured TCP position and target // direction in Base. Useful for distance-based motion without caller FK. @@ -96,37 +100,6 @@ struct CartesianWrench { double tz{0.0}; }; -struct JointLimit { - double lower{0.0}; - double upper{0.0}; - double max_velocity{0.0}; - double max_acceleration{0.0}; - double max_torque{0.0}; -}; - -struct RobotModel { - std::string name; - std::string subtype; - std::string manufacturer; - std::string serial_number; - std::string description_id; - std::string default_base_frame; - std::string default_tcp_frame; - bool detected_from_sdk{false}; - std::size_t dof{0}; - std::vector joint_names; - std::vector joint_limits; - double max_tcp_speed{0.0}; - double max_tcp_acceleration{0.0}; - double max_payload{0.0}; - - bool valid() const - { - return dof > 0 && joint_names.size() == dof && - (joint_limits.empty() || joint_limits.size() == dof); - } -}; - struct JointGroupState { std::vector position; std::vector velocity; @@ -146,6 +119,9 @@ struct JointTrajectoryPoint { double time_s{0.0}; std::vector position; std::vector velocity; + // Analytic derivatives; empty for trajectories without these derivatives. + std::vector acceleration; + std::vector jerk; }; using JointTrajectory = std::vector; @@ -192,12 +168,21 @@ struct MotionOptions { double velocity{0.0}; double acceleration{0.0}; double blend_radius{0.0}; - double jerk{5.0}; + double jerk{300.0}; std::vector joint_velocity_limits; bool asynchronous{false}; // Optional cooperative cancellation used by synchronous ActionQueue // motion. Drivers must not retain this callback after the command returns. std::function cancellation_requested; + // MoveJ/MoveP: called once with the validated trajectory, before execution. + // Runs synchronously; copy the data here and perform file I/O after motion. + std::function trajectory_callback; + // Optional MoveP constraint on the TCP pose in Base coordinates. Checked + // during joint-path search and discrete smoothed-trajectory validation. + // Runs synchronously and must return quickly; false rejects the sampled + // state. This checks the TCP only, not the complete robot geometry. + // Drivers must reject unsupported constraints and never retain this callback. + std::function is_tcp_pose_valid; }; struct ServoOptions { diff --git a/cmvr-es/config/devices/arm/tchl_arm.pb.txt b/cmvr-es/config/devices/arm/tchl_arm.pb.txt index 76126848..caddff1c 100644 --- a/cmvr-es/config/devices/arm/tchl_arm.pb.txt +++ b/cmvr-es/config/devices/arm/tchl_arm.pb.txt @@ -1,4 +1,4 @@ -# 六轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。 +# 七轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。 arm { robot_arms { id: "tchl_arm" @@ -6,29 +6,24 @@ arm { motor { motor_system_id: "tchl_joint_motors" motor_group_ids: "tchl_joint_motors" - dof: 6 + dof: 7 joint_names: "TCHL_AXIS_1" joint_names: "TCHL_AXIS_2" joint_names: "TCHL_AXIS_3" joint_names: "TCHL_AXIS_4" joint_names: "TCHL_AXIS_5" joint_names: "TCHL_AXIS_6" + joint_names: "TCHL_AXIS_7" upd_freq: 1000 } motion { - # 保持 linbo_dev 的 TOPPRA 规划器,不引入另一分支的规划接口。 + # 与 lgv_dev_tc_motor 一致:默认五次 B 样条平滑,采样周期 1 ms。 move_j { settle_timeout_s: 2.0 settle_position_tolerance_rad: 0.002 settle_velocity_tolerance_rad_s: 0.02 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } } } diff --git a/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt b/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt index bc85319e..c528c9ec 100644 --- a/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt +++ b/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt @@ -31,6 +31,7 @@ motor { slaves { motor_id: 4 alias: 0 position: 3 } slaves { motor_id: 5 alias: 0 position: 4 } slaves { motor_id: 6 alias: 0 position: 5 } + slaves { motor_id: 7 alias: 0 position: 6 } } @@ -44,7 +45,8 @@ motor { joints { joint_name: "TCHL_AXIS_3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } joints { joint_name: "TCHL_AXIS_4" q_lb: -2.04 q_ub: 1.10 qd: 5.0 qdd: 10.0 } joints { joint_name: "TCHL_AXIS_5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } - joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 0.21 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_7" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } } @@ -55,6 +57,7 @@ motor { motors { id: 4 joint_name: "TCHL_AXIS_4" encoder_counts_per_rev: 131072 gear_ratio: 101 } motors { id: 5 joint_name: "TCHL_AXIS_5" encoder_counts_per_rev: 131072 gear_ratio: 101 } motors { id: 6 joint_name: "TCHL_AXIS_6" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 7 joint_name: "TCHL_AXIS_7" encoder_counts_per_rev: 131072 gear_ratio: 101 } } } diff --git a/cmvr-es/curves/CMakeLists.txt b/cmvr-es/curves/CMakeLists.txt new file mode 100644 index 00000000..1bc714de --- /dev/null +++ b/cmvr-es/curves/CMakeLists.txt @@ -0,0 +1,10 @@ +find_package(Eigen3 CONFIG REQUIRED) + +add_library(curves SHARED + bspline/src/quintic_bspline.cpp + s_curve/src/s_curve.cpp +) +target_include_directories(curves PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..") +target_link_libraries(curves PUBLIC Eigen3::Eigen) +add_library(cmvr_es::curves ALIAS curves) +install(TARGETS curves LIBRARY DESTINATION lib) diff --git a/cmvr-es/curves/bspline/include/quintic_bspline.h b/cmvr-es/curves/bspline/include/quintic_bspline.h new file mode 100644 index 00000000..08ae3d8c --- /dev/null +++ b/cmvr-es/curves/bspline/include/quintic_bspline.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace cmvr { + +// A time-domain degree-five B-spline with analytic derivatives. The input +// polyline guides the control points; intermediate waypoints are not exact +// interpolation constraints. The caller must collision-check the resulting +// curve, which can cut corners of the input path. +class QuinticBSpline final { +public: + // Limits are positive per-joint magnitudes in rad/s, rad/s^2 and rad/s^3. + // Duration is uniformly increased until derivative control-point bounds + // satisfy all limits. Start/end positions are exact, with zero v and a. + // control_point_spacing_rad sets the positive joint-space reference spacing. + // Invalid input throws invalid_argument; cancellation/numerical failure + // throws runtime_error. A stationary path uses minimum_duration_s. + static std::shared_ptr create( + const std::vector>& waypoints, + const std::vector& velocity_limits, + const std::vector& acceleration_limits, + const std::vector& jerk_limits, + double minimum_duration_s, + const std::function& cancelled = {}, + double control_point_spacing_rad = 0.05); + + Eigen::RowVector2d timeInterval() const; + // Finite times are clamped to the trajectory interval. NaN/Inf are invalid. + Eigen::VectorXd q(double t) const; + Eigen::VectorXd qd(double t) const; + Eigen::VectorXd qdd(double t) const; + Eigen::VectorXd qddd(double t) const; + std::vector knotTimes() const; + + // Conservative absolute bounds over the whole trajectory, orders 0..3. + Eigen::VectorXd derivativeBounds(int order) const; + // Each column is one control point. Knots use normalized time [0, 1]. + const Eigen::MatrixXd& controlPoints() const { return controls_[0]; } + const std::vector& knots() const { return knots_[0]; } + +private: + QuinticBSpline() = default; + Eigen::VectorXd evaluate(double t, int order) const; + + std::array controls_; + std::array, 4> knots_; + double duration_s_{0.0}; +}; + +} // namespace cmvr diff --git a/cmvr-es/curves/bspline/src/quintic_bspline.cpp b/cmvr-es/curves/bspline/src/quintic_bspline.cpp new file mode 100644 index 00000000..c92d86b8 --- /dev/null +++ b/cmvr-es/curves/bspline/src/quintic_bspline.cpp @@ -0,0 +1,264 @@ +#include "curves/bspline/include/quintic_bspline.h" + +#include +#include +#include +#include + +namespace cmvr { +namespace { + +constexpr int kDegree = 5; +constexpr std::size_t kMaxControlPoints = 10000; +constexpr double kSmoothstepMaximumSlope = 1.875; +constexpr double kDurationMargin = 1.001; + +void checkCancelled(const std::function& cancelled) +{ + if (cancelled && cancelled()) { + throw std::runtime_error("B-spline planning cancelled"); + } +} + +void validateLimits(const std::vector& limits, std::size_t dof) +{ + if (limits.size() != dof || + !std::all_of(limits.begin(), limits.end(), [](double value) { + return std::isfinite(value) && value > 0.0; + })) { + throw std::invalid_argument("B-spline limits must be positive, finite and match the DOF"); + } +} + +// The degree-five blossom of 10u^3-15u^4+6u^5 is e3-3e4+6e5, +// where ek is the elementary symmetric polynomial of the five arguments. +// Thus a straight reference path reproduces one global minimum-jerk quintic, +// rather than acquiring speed ripples from a uniform spatial control polygon. +double smoothstepControl(const std::vector& knots, std::size_t index) +{ + const bool mirror = knots[index + 3] > 0.5; + std::array elementary{}; + elementary[0] = 1.0; + for (int argument = 1; argument <= kDegree; ++argument) { + const double value = mirror ? 1.0 - knots[index + argument] : knots[index + argument]; + for (int order = argument; order >= 1; --order) { + elementary[order] += value * elementary[order - 1]; + } + } + const double progress = elementary[3] - 3.0 * elementary[4] + 6.0 * elementary[5]; + return std::clamp(mirror ? 1.0 - progress : progress, 0.0, 1.0); +} + +} // namespace + +std::shared_ptr QuinticBSpline::create( + const std::vector>& waypoints, + const std::vector& velocity_limits, + const std::vector& acceleration_limits, + const std::vector& jerk_limits, + double minimum_duration_s, + const std::function& cancelled, + double control_point_spacing_rad) +{ + if (waypoints.empty() || waypoints.size() > kMaxControlPoints || + waypoints.front().empty() || !std::isfinite(minimum_duration_s) || + minimum_duration_s <= 0.0) { + throw std::invalid_argument("B-spline requires a nonempty path and positive finite duration"); + } + if (!std::isfinite(control_point_spacing_rad) || control_point_spacing_rad <= 0.0) { + throw std::invalid_argument("B-spline control-point spacing must be positive and finite"); + } + const auto dof = waypoints.front().size(); + if (dof > static_cast(std::numeric_limits::max())) { + throw std::invalid_argument("B-spline DOF is too large"); + } + validateLimits(velocity_limits, dof); + validateLimits(acceleration_limits, dof); + validateLimits(jerk_limits, dof); + checkCancelled(cancelled); + + std::vector vertices; + std::vector chord_lengths; + vertices.reserve(waypoints.size()); + chord_lengths.reserve(waypoints.size()); + double length = 0.0; + for (const auto& waypoint : waypoints) { + checkCancelled(cancelled); + if (waypoint.size() != dof || + !std::all_of(waypoint.begin(), waypoint.end(), [](double value) { + return std::isfinite(value); + })) { + throw std::invalid_argument("B-spline waypoints must be finite and have matching DOF"); + } + Eigen::VectorXd vertex = Eigen::Map( + waypoint.data(), static_cast(dof)); + if (!vertices.empty()) { + const Eigen::VectorXd delta = vertex - vertices.back(); + const double distance = delta.stableNorm(); + if (!std::isfinite(distance)) { + throw std::invalid_argument("B-spline path length is not finite"); + } + if (distance == 0.0) { + continue; + } + length += distance; + if (!std::isfinite(length)) { + throw std::invalid_argument("B-spline path length is not finite"); + } + } + vertices.push_back(std::move(vertex)); + chord_lengths.push_back(length); + } + + // Three equal controls at each clamped endpoint impose q'=q''=0 without + // stopping at any of the interior reference points. + // Check the floating-point count before conversion, including tiny spacing. + const long double interval_count = std::ceil( + static_cast(length) * kSmoothstepMaximumSlope / control_point_spacing_rad); + if (!std::isfinite(interval_count) || interval_count > kMaxControlPoints - kDegree) { + throw std::invalid_argument("B-spline path exceeds the control-point limit"); + } + const auto intervals = std::max(1, static_cast(interval_count)); + const auto control_count = intervals + kDegree; + auto trajectory = std::shared_ptr(new QuinticBSpline); + auto& knots = trajectory->knots_[0]; + knots.assign(control_count + kDegree + 1, 0.0); + for (std::size_t i = kDegree + 1; i < control_count; ++i) { + knots[i] = static_cast(i - kDegree) / intervals; + } + std::fill(knots.begin() + static_cast(control_count), knots.end(), 1.0); + + auto& controls = trajectory->controls_[0]; + controls.resize(static_cast(dof), static_cast(control_count)); + for (int i = 0; i < 3; ++i) { + controls.col(i) = vertices.front(); + controls.col(static_cast(control_count) - 1 - i) = vertices.back(); + } + std::size_t segment = 1; + for (std::size_t i = 3; i + 3 < control_count; ++i) { + checkCancelled(cancelled); + const double distance = length * smoothstepControl(knots, i); + while (segment + 1 < vertices.size() && chord_lengths[segment] < distance) { + ++segment; + } + const double alpha = std::clamp( + (distance - chord_lengths[segment - 1]) / + (chord_lengths[segment] - chord_lengths[segment - 1]), + 0.0, 1.0); + controls.col(static_cast(i)) = + vertices[segment - 1] + alpha * (vertices[segment] - vertices[segment - 1]); + } + + // Differentiating a B-spline gives another B-spline: fewer controls, lower + // degree, and the first/last knot removed at each derivative order. + for (int order = 1; order <= 3; ++order) { + const auto& previous_controls = trajectory->controls_[order - 1]; + const auto& previous_knots = trajectory->knots_[order - 1]; + const int previous_degree = kDegree - order + 1; + auto& derivative_controls = trajectory->controls_[order]; + derivative_controls.resize(previous_controls.rows(), previous_controls.cols() - 1); + trajectory->knots_[order].assign(previous_knots.begin() + 1, previous_knots.end() - 1); + for (Eigen::Index i = 0; i < derivative_controls.cols(); ++i) { + checkCancelled(cancelled); + const double span = previous_knots[i + previous_degree + 1] - previous_knots[i + 1]; + derivative_controls.col(i) = + (previous_controls.col(i + 1) - previous_controls.col(i)) * (previous_degree / span); + } + if (!derivative_controls.allFinite()) { + throw std::runtime_error("B-spline derivatives are not finite"); + } + } + + // The derivative curve lies in the convex hull of its derivative controls, + // so these bounds hold continuously, including between controller samples. + long double required_duration = 0.0L; + for (int order = 1; order <= 3; ++order) { + const auto& limits = order == 1 ? velocity_limits : + order == 2 ? acceleration_limits : jerk_limits; + const Eigen::VectorXd bounds = trajectory->controls_[order].cwiseAbs().rowwise().maxCoeff(); + for (Eigen::Index joint = 0; joint < bounds.size(); ++joint) { + const long double ratio = static_cast(bounds[joint]) / limits[joint]; + const long double duration = order == 1 ? ratio : + order == 2 ? std::sqrt(ratio) : std::cbrt(ratio); + required_duration = std::max(required_duration, duration); + } + } + const long double duration = std::max( + static_cast(minimum_duration_s), required_duration * kDurationMargin); + if (!std::isfinite(duration) || duration > std::numeric_limits::max()) { + throw std::runtime_error("B-spline duration is not representable"); + } + trajectory->duration_s_ = static_cast(duration); + checkCancelled(cancelled); + return trajectory; +} + +Eigen::RowVector2d QuinticBSpline::timeInterval() const +{ + return {0.0, duration_s_}; +} + +Eigen::VectorXd QuinticBSpline::evaluate(double t, int order) const +{ + if (!std::isfinite(t)) { + throw std::invalid_argument("B-spline evaluation time must be finite"); + } + const auto& controls = controls_[order]; + const auto& knots = knots_[order]; + const int degree = kDegree - order; + const double u = std::clamp(t, 0.0, duration_s_) / duration_s_; + Eigen::VectorXd result; + if (u <= 0.0) { + result = controls.col(0); + } else if (u >= 1.0) { + result = controls.col(controls.cols() - 1); + } else { + const auto span = static_cast( + std::upper_bound(knots.begin(), knots.end(), u) - knots.begin() - 1); + Eigen::MatrixXd work = controls.middleCols(span - degree, degree + 1); + for (int level = 1; level <= degree; ++level) { + for (int j = degree; j >= level; --j) { + const auto left = span - degree + j; + const double alpha = (u - knots[left]) / + (knots[span + j - level + 1] - knots[left]); + work.col(j) = work.col(j - 1) + alpha * (work.col(j) - work.col(j - 1)); + } + } + result = work.col(degree); + } + for (int derivative = 0; derivative < order; ++derivative) { + result /= duration_s_; + } + return result; +} + +Eigen::VectorXd QuinticBSpline::q(double t) const { return evaluate(t, 0); } +Eigen::VectorXd QuinticBSpline::qd(double t) const { return evaluate(t, 1); } +Eigen::VectorXd QuinticBSpline::qdd(double t) const { return evaluate(t, 2); } +Eigen::VectorXd QuinticBSpline::qddd(double t) const { return evaluate(t, 3); } + +std::vector QuinticBSpline::knotTimes() const +{ + std::vector times; + for (double knot : knots_[0]) { + const double time = knot * duration_s_; + if (times.empty() || time != times.back()) { + times.push_back(time); + } + } + return times; +} + +Eigen::VectorXd QuinticBSpline::derivativeBounds(int order) const +{ + if (order < 0 || order > 3) { + throw std::invalid_argument("B-spline derivative order must be between zero and three"); + } + Eigen::VectorXd bounds = controls_[order].cwiseAbs().rowwise().maxCoeff(); + for (int derivative = 0; derivative < order; ++derivative) { + bounds /= duration_s_; + } + return bounds; +} + +} // namespace cmvr diff --git a/cmvr-es/curves/s_curve/include/s_curve.h b/cmvr-es/curves/s_curve/include/s_curve.h new file mode 100644 index 00000000..59638653 --- /dev/null +++ b/cmvr-es/curves/s_curve/include/s_curve.h @@ -0,0 +1,262 @@ +// +// Created by lgv on 2026/3/2. +// +/** + * @file s_curve.h + * @brief 位置与速度 S 曲线的数学计算 + * + * 实现标准 7 段式位置 S 曲线速度剖面: + * 1. 加加速度上升段(加速度逐渐增大) + * 2. 匀加速段 + * 3. 加加速度下降段(加速度逐渐降到 0) + * 4. 匀速巡航段 + * 5. 加加速度下降段(减速度逐渐增大) + * 6. 匀减速段 + * 7. 加加速度上升段(减速度逐渐降到 0) + * + * 同时支持三段式速度切换剖面。只负责剖面计算与按时间采样, + * 不保存运行状态,不负责实时目标更新、周期推进或反馈同步。 + */ + +#pragma once + +#include +#include +#include + + +namespace cmvr +{ + +/** + * @brief 单次点到点运动的 S 曲线剖面参数 + */ +struct LgvSCurveProfile +{ + // 7 个阶段的持续时间 + double t1; // 加加速度上升时间(加速阶段) + double t2; // 匀加速时间 + double t3; // 加加速度下降时间(加速阶段结束) + double t4; // 匀速时间(巡航) + double t5; // 加加速度下降时间(减速阶段) + double t6; // 匀减速时间 + double t7; // 加加速度上升时间(减速阶段结束) + + double total_time; + + // 运动约束 + double j_max; // 最大加加速度 (rad/s³) + double a_max; // 最大加速度 (rad/s²) + double v_max; // 最大速度 (rad/s) + + // 运动参数 + double distance; // 运动总距离 + double direction; // +1 或 -1 + double v_cruise; // 实际达到的巡航速度 + double a_limit; // 实际达到的加速度上限 + + // 初始条件 + double p0; // 初始位置 + double v0; // 初始速度 + double a0; // 初始加速度 + double vf; // 终止速度 + + LgvSCurveProfile() + : t1(0), t2(0), t3(0), t4(0), t5(0), t6(0), t7(0) + , total_time(0) + , j_max(50.0), a_max(10.0), v_max(3.0) + , distance(0), direction(1.0), v_cruise(0), a_limit(0) + , p0(0), v0(0), a0(0), vf(0) + {} +}; + +/** + * @brief 单次速度切换的 S 曲线剖面参数 + * + * 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile: + * + * seg1: jerk = j1, duration = t1 + * seg2: jerk = j2, duration = t2 (当前实现 j2 = 0) + * seg3: jerk = j3, duration = t3 + * + * 其中 j1/j3 为 ±j_max,j2 为 0。 + */ +struct LgvSCurveVelocityProfile +{ + double t1; + double t2; + double t3; + + double total_time; + + double j1; + double j2; + double j3; + + double v0; + double a0; + double vf; + + bool valid; + + LgvSCurveVelocityProfile() + : t1(0.0), t2(0.0), t3(0.0) + , total_time(0.0) + , j1(0.0), j2(0.0), j3(0.0) + , v0(0.0), a0(0.0), vf(0.0) + , valid(false) + {} +}; + +/** + * @brief 位置与速度 S 曲线的数学计算和采样,不保存运行状态 + */ +class LgvSCurve +{ +public: + /** + * @brief 构造函数(带运动约束) + * @param max_velocity 最大速度 (rad/s) + * @param max_acceleration 最大加速度 (rad/s²) + * @param max_jerk 最大加加速度 (rad/s³) + */ + LgvSCurve(double max_velocity = 3.0, + double max_acceleration = 10.0, + double max_jerk = 50.0); + + /** + * @brief 设置运动约束 + */ + void setConstraints(double max_velocity, double max_acceleration, double max_jerk); + + /** + * @brief 获取当前运动约束 + */ + void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const; + + /** + * @brief 计算点到点运动的完整 S 曲线剖面 + * @param start_position 起始位置 + * @param end_position 终止位置 + * @param start_velocity 起始速度(默认 0) + * @param end_velocity 终止速度(默认 0) + * @return 计算得到的剖面参数 + */ + LgvSCurveProfile calculatePositionProfile(double start_position, double end_position, + double start_velocity = 0.0, + double end_velocity = 0.0) const; + + /** + * @brief 给定剖面下,获取时刻 t 的位置 + * @param profile S 曲线剖面 + * @param t 从起点开始的时间 + * @return 时刻 t 的位置 + */ + double getPositionAtTime(const LgvSCurveProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的速度 + * @param profile S 曲线剖面 + * @param t 从起点开始的时间 + * @return 时刻 t 的速度 + */ + double getVelocityAtTime(const LgvSCurveProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的加速度 + * @param profile S 曲线剖面 + * @param t 从起点开始的时间 + * @return 时刻 t 的加速度 + */ + double getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的加加速度 + * @param profile S 曲线剖面 + * @param t 从起点开始的时间 + * @return 时刻 t 的加加速度 + */ + double getJerkAtTime(const LgvSCurveProfile& profile, double t) const; + + /** + * @brief 按固定时间间隔生成轨迹点 + * @param profile S 曲线剖面 + * @param dt 轨迹点时间间隔 + * @param positions 输出:每个时间点的位置 + * @param velocities 输出:每个时间点的速度 + * @param accelerations 输出:每个时间点的加速度 + */ + void generateTrajectory(const LgvSCurveProfile& profile, double dt, + std::vector& positions, + std::vector& velocities, + std::vector& accelerations) const; + + /** + * @brief 计算单次速度切换剖面 + */ + LgvSCurveVelocityProfile calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration = 0.0) const; + + /** + * @brief 给定剖面下,获取时刻 t 的速度 + */ + double getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的加速度 + */ + double getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的 jerk + */ + double getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const; + + /** + * @brief 按固定时间间隔生成轨迹点 + */ + void generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt, + std::vector& velocities, + std::vector& accelerations, + std::vector& jerks) const; + +private: + double max_velocity_; + double max_acceleration_; + double max_jerk_; + + static constexpr double EPSILON = 1e-9; + static constexpr double VELOCITY_THRESHOLD = 1e-6; + static constexpr double ACCELERATION_THRESHOLD = 1e-6; + + double computeSegmentJerk(const LgvSCurveProfile& profile, double t) const; + void calculateShortProfile(LgvSCurveProfile& profile) const; + void calculateLongProfile(LgvSCurveProfile& profile) const; + + /** + * @brief 判断 profile 是否满足速度上限 + */ + bool isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const; + + /** + * @brief 计算完整剖面终点状态 + */ + void integrateWholeProfile(const LgvSCurveVelocityProfile& profile, + double& v_end, + double& a_end) const; + + static double clamp(double value, double min_val, double max_val) + { + return std::max(min_val, std::min(max_val, value)); + } + + static double sign(double value) + { + if (value > EPSILON) return 1.0; + if (value < -EPSILON) return -1.0; + return 0.0; + } +}; + +} // namespace cmvr diff --git a/cmvr-es/curves/s_curve/src/s_curve.cpp b/cmvr-es/curves/s_curve/src/s_curve.cpp new file mode 100644 index 00000000..37bc5ceb --- /dev/null +++ b/cmvr-es/curves/s_curve/src/s_curve.cpp @@ -0,0 +1,874 @@ +// +// Created by lgv on 2026/3/2. +// + + +/** + * @file s_curve.cpp + * @brief 位置与速度 S 曲线数学实现 + */ + +#include "curves/s_curve/include/s_curve.h" +#include +#include +#include + +namespace cmvr +{ +LgvSCurve::LgvSCurve(double max_velocity, double max_acceleration, double max_jerk) + : max_velocity_(std::abs(max_velocity)) + , max_acceleration_(std::abs(max_acceleration)) + , max_jerk_(std::abs(max_jerk)) +{} + +void LgvSCurve::setConstraints(double max_velocity, double max_acceleration, double max_jerk) +{ + max_velocity_ = std::abs(max_velocity); + max_acceleration_ = std::abs(max_acceleration); + max_jerk_ = std::abs(max_jerk); +} + +void LgvSCurve::getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const +{ + max_velocity = max_velocity_; + max_acceleration = max_acceleration_; + max_jerk = max_jerk_; +} + +LgvSCurveProfile LgvSCurve::calculatePositionProfile(double start_position, double end_position, + double start_velocity, double end_velocity) const +{ + LgvSCurveProfile profile; + profile.j_max = max_jerk_; + profile.a_max = max_acceleration_; + profile.v_max = max_velocity_; + profile.p0 = start_position; + profile.v0 = start_velocity; + profile.a0 = 0.0; // Assume starting from zero acceleration + profile.vf = end_velocity; + + double displacement = end_position - start_position; + profile.distance = std::abs(displacement); + profile.direction = (displacement >= 0) ? 1.0 : -1.0; + + if (profile.distance < EPSILON) { + // 无需运动 + profile.total_time = 0.0; + return profile; + } + + const double start_speed = profile.direction * start_velocity; + const double end_speed = profile.direction * end_velocity; + if (start_speed < -VELOCITY_THRESHOLD || end_speed < -VELOCITY_THRESHOLD) { + profile.total_time = 0.0; + return profile; + } + + if (std::abs(start_speed) > VELOCITY_THRESHOLD || + std::abs(end_speed) > VELOCITY_THRESHOLD) { + auto calc_transition = [&](double v_from, double v_to, + double& t_j, double& t_a, + double& duration, double& distance) { + t_j = 0.0; + t_a = 0.0; + duration = 0.0; + distance = 0.0; + + const double dv = std::abs(v_to - v_from); + if (dv <= 1e-12 || profile.a_max <= 1e-12 || profile.j_max <= 1e-12) { + return; + } + + const double dv_switch = profile.a_max * profile.a_max / profile.j_max; + if (dv < dv_switch) { + t_j = std::sqrt(dv / profile.j_max); + t_a = 0.0; + } else { + t_j = profile.a_max / profile.j_max; + t_a = dv / profile.a_max - t_j; + } + + duration = 2.0 * t_j + t_a; + distance = 0.5 * (v_from + v_to) * duration; + }; + + const double v_cap = std::max({profile.v_max, start_speed, end_speed}); + const double v_peak_min = std::max(start_speed, end_speed); + + double acc_tj = 0.0, acc_ta = 0.0, acc_duration = 0.0, acc_distance = 0.0; + double dec_tj = 0.0, dec_ta = 0.0, dec_duration = 0.0, dec_distance = 0.0; + calc_transition(start_speed, v_peak_min, + acc_tj, acc_ta, acc_duration, acc_distance); + calc_transition(v_peak_min, end_speed, + dec_tj, dec_ta, dec_duration, dec_distance); + const double d_min = acc_distance + dec_distance; + if (profile.distance + EPSILON < d_min) { + profile.total_time = 0.0; + return profile; + } + + calc_transition(start_speed, v_cap, + acc_tj, acc_ta, acc_duration, acc_distance); + calc_transition(v_cap, end_speed, + dec_tj, dec_ta, dec_duration, dec_distance); + const double d_cap = acc_distance + dec_distance; + + double v_peak = v_cap; + double t4 = 0.0; + + if (profile.distance > d_cap + EPSILON) { + t4 = (profile.distance - d_cap) / std::max(v_peak, EPSILON); + } else { + double lo = v_peak_min; + double hi = v_cap; + for (int iter = 0; iter < 80; ++iter) { + const double mid = 0.5 * (lo + hi); + double mid_acc_tj = 0.0, mid_acc_ta = 0.0, mid_acc_duration = 0.0, mid_acc_distance = 0.0; + double mid_dec_tj = 0.0, mid_dec_ta = 0.0, mid_dec_duration = 0.0, mid_dec_distance = 0.0; + calc_transition(start_speed, mid, + mid_acc_tj, mid_acc_ta, mid_acc_duration, mid_acc_distance); + calc_transition(mid, end_speed, + mid_dec_tj, mid_dec_ta, mid_dec_duration, mid_dec_distance); + const double d_mid = mid_acc_distance + mid_dec_distance; + if (d_mid < profile.distance) { + lo = mid; + } else { + hi = mid; + } + } + v_peak = hi; + calc_transition(start_speed, v_peak, + acc_tj, acc_ta, acc_duration, acc_distance); + calc_transition(v_peak, end_speed, + dec_tj, dec_ta, dec_duration, dec_distance); + } + + profile.t1 = acc_tj; + profile.t2 = acc_ta; + profile.t3 = acc_tj; + profile.t4 = t4; + profile.t5 = dec_tj; + profile.t6 = dec_ta; + profile.t7 = dec_tj; + profile.v_cruise = v_peak; + profile.a_limit = std::max(profile.j_max * profile.t1, profile.j_max * profile.t5); + profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 + + profile.t5 + profile.t6 + profile.t7; + return profile; + } + + const double j = profile.j_max; + const double a = profile.a_max; + const double v = profile.v_max; + const double t_j_a = a / j; + + if (v < a * t_j_a) { + const double t_j_v = std::sqrt(v / j); + const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v; + if (profile.distance > s_min + EPSILON) { + calculateLongProfile(profile); + } else { + calculateShortProfile(profile); + } + } else { + const double t_a_v = v / a - t_j_a; + const double s_half_v = + a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a_v + 0.5 * t_a_v * t_a_v); + const double s_min = 2.0 * s_half_v; + if (profile.distance > s_min + EPSILON) { + calculateLongProfile(profile); + } else { + calculateShortProfile(profile); + } + } + + return profile; +} + +void LgvSCurve::calculateShortProfile(LgvSCurveProfile& profile) const +{ + // 短距离:无巡航段(t4 = 0)。 + const double j = profile.j_max; + const double a = profile.a_max; + const double v = profile.v_max; + const double d = profile.distance; + const double t_j_a = a / j; + + if (v < a * t_j_a) { + // 达不到 a_max:极短距离时只有 4 个 jerk 段。 + const double t1 = std::cbrt(d / (2.0 * j)); + profile.t1 = t1; + profile.t2 = 0.0; + profile.t3 = t1; + profile.t4 = 0.0; + profile.t5 = t1; + profile.t6 = 0.0; + profile.t7 = t1; + profile.v_cruise = j * t1 * t1; + profile.a_limit = j * t1; + } else { + // 能达到 a_max,但达不到 v_max:求无巡航的匀加速持续时间。 + const double D = t_j_a * t_j_a + 4.0 * (d / a); + double t2 = (-3.0 * t_j_a + std::sqrt(std::max(0.0, D))) * 0.5; + + if (t2 < 0.0) { + const double t1 = std::cbrt(d / (2.0 * j)); + profile.t1 = t1; + profile.t2 = 0.0; + profile.t3 = t1; + profile.t4 = 0.0; + profile.t5 = t1; + profile.t6 = 0.0; + profile.t7 = t1; + profile.v_cruise = j * t1 * t1; + profile.a_limit = j * t1; + } else { + profile.t1 = t_j_a; + profile.t2 = t2; + profile.t3 = t_j_a; + profile.t4 = 0.0; + profile.t5 = t_j_a; + profile.t6 = t2; + profile.t7 = t_j_a; + profile.v_cruise = a * (t2 + t_j_a); + profile.a_limit = a; + } + } + + profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 + + profile.t5 + profile.t6 + profile.t7; +} + +void LgvSCurve::calculateLongProfile(LgvSCurveProfile& profile) const +{ + // 含巡航段的完整 7 段式 S 曲线;与 LgvSCurveProfile1D 的 full-profile 公式一致。 + const double j = profile.j_max; + const double a = profile.a_max; + const double v = profile.v_max; + const double d = profile.distance; + const double t_j_a = a / j; + + if (v < a * t_j_a) { + // 达不到 a_max,但可以达到 v_max 并进入巡航。 + const double t_j_v = std::sqrt(v / j); + const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v; + profile.t1 = t_j_v; + profile.t2 = 0.0; + profile.t3 = t_j_v; + profile.t4 = std::max(0.0, (d - s_min) / v); + profile.t5 = t_j_v; + profile.t6 = 0.0; + profile.t7 = t_j_v; + profile.v_cruise = v; + profile.a_limit = j * t_j_v; + } else { + // 能达到 a_max 和 v_max。 + const double t_a = v / a - t_j_a; + const double s_half = + a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a + 0.5 * t_a * t_a); + const double s_min = 2.0 * s_half; + + profile.t1 = t_j_a; + profile.t2 = t_a; + profile.t3 = t_j_a; + profile.t4 = std::max(0.0, (d - s_min) / v); + profile.t5 = t_j_a; + profile.t6 = t_a; + profile.t7 = t_j_a; + profile.v_cruise = v; + profile.a_limit = a; + } + + profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 + + profile.t5 + profile.t6 + profile.t7; +} + +double LgvSCurve::computeSegmentJerk(const LgvSCurveProfile& profile, double t) const +{ + double j = profile.j_max * profile.direction; + + // 判断所处阶段 + double t_end1 = profile.t1; + double t_end2 = t_end1 + profile.t2; + double t_end3 = t_end2 + profile.t3; + double t_end4 = t_end3 + profile.t4; + double t_end5 = t_end4 + profile.t5; + double t_end6 = t_end5 + profile.t6; + // double t_end7 = t_end6 + profile.t7; // = total_time + + if (t < t_end1) { + return j; // 段 1:正加加速度(加速) + } else if (t < t_end2) { + return 0.0; // 段 2:加加速度为 0(匀加速) + } else if (t < t_end3) { + return -j; // 段 3:负加加速度(减小加速度) + } else if (t < t_end4) { + return 0.0; // 段 4:加加速度为 0(巡航) + } else if (t < t_end5) { + return -j; // 段 5:负加加速度(开始减速) + } else if (t < t_end6) { + return 0.0; // 段 6:加加速度为 0(匀减速) + } else { + return j; // 段 7:正加加速度(减速结束) + } +} + +double LgvSCurve::getPositionAtTime(const LgvSCurveProfile& profile, double t) const +{ + if (t <= 0) return profile.p0; + if (t >= profile.total_time) return profile.p0 + profile.distance * profile.direction; + + double j = profile.j_max * profile.direction; + double p = profile.p0; + double v = profile.v0; + double a = profile.a0; + + // 时间边界 + double t_end1 = profile.t1; + double t_end2 = t_end1 + profile.t2; + double t_end3 = t_end2 + profile.t3; + double t_end4 = t_end3 + profile.t4; + double t_end5 = t_end4 + profile.t5; + double t_end6 = t_end5 + profile.t6; + + // 依次处理各阶段 + auto processSegment = [&](double dt, double jerk) { + p += v * dt + 0.5 * a * dt * dt + (1.0/6.0) * jerk * dt * dt * dt; + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + // 段 1 + if (t <= t_end1) { + processSegment(t, j); + return p; + } + processSegment(profile.t1, j); + + // 段 2 + if (t <= t_end2) { + processSegment(t - t_end1, 0.0); + return p; + } + processSegment(profile.t2, 0.0); + + // 段 3 + if (t <= t_end3) { + processSegment(t - t_end2, -j); + return p; + } + processSegment(profile.t3, -j); + + // 段 4(巡航) + if (t <= t_end4) { + processSegment(t - t_end3, 0.0); + return p; + } + processSegment(profile.t4, 0.0); + + // 段 5 + if (t <= t_end5) { + processSegment(t - t_end4, -j); + return p; + } + processSegment(profile.t5, -j); + + // 段 6 + if (t <= t_end6) { + processSegment(t - t_end5, 0.0); + return p; + } + processSegment(profile.t6, 0.0); + + // 段 7 + processSegment(t - t_end6, j); + return p; +} + +double LgvSCurve::getVelocityAtTime(const LgvSCurveProfile& profile, double t) const +{ + if (t <= 0) return profile.v0; + if (t >= profile.total_time) return profile.vf; + + double j = profile.j_max * profile.direction; + double v = profile.v0; + double a = profile.a0; + + // 时间边界 + double t_end1 = profile.t1; + double t_end2 = t_end1 + profile.t2; + double t_end3 = t_end2 + profile.t3; + double t_end4 = t_end3 + profile.t4; + double t_end5 = t_end4 + profile.t5; + double t_end6 = t_end5 + profile.t6; + + auto processSegment = [&](double dt, double jerk) { + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + if (t <= t_end1) { + v += a * t + 0.5 * j * t * t; + return v; + } + processSegment(profile.t1, j); + + if (t <= t_end2) { + v += a * (t - t_end1); + return v; + } + processSegment(profile.t2, 0.0); + + if (t <= t_end3) { + double dt = t - t_end2; + v += a * dt + 0.5 * (-j) * dt * dt; + return v; + } + processSegment(profile.t3, -j); + + if (t <= t_end4) { + v += a * (t - t_end3); + return v; + } + processSegment(profile.t4, 0.0); + + if (t <= t_end5) { + double dt = t - t_end4; + v += a * dt + 0.5 * (-j) * dt * dt; + return v; + } + processSegment(profile.t5, -j); + + if (t <= t_end6) { + v += a * (t - t_end5); + return v; + } + processSegment(profile.t6, 0.0); + + double dt = t - t_end6; + v += a * dt + 0.5 * j * dt * dt; + return v; +} + +double LgvSCurve::getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const +{ + if (t <= 0 || t >= profile.total_time) return 0.0; + + double j = profile.j_max * profile.direction; + double a = profile.a0; + + // 时间边界 + double t_end1 = profile.t1; + double t_end2 = t_end1 + profile.t2; + double t_end3 = t_end2 + profile.t3; + double t_end4 = t_end3 + profile.t4; + double t_end5 = t_end4 + profile.t5; + double t_end6 = t_end5 + profile.t6; + + if (t <= t_end1) { + return a + j * t; + } + a += j * profile.t1; + + if (t <= t_end2) { + return a; + } + + if (t <= t_end3) { + return a + (-j) * (t - t_end2); + } + a += (-j) * profile.t3; + + if (t <= t_end4) { + return a; // Should be ~0 + } + + if (t <= t_end5) { + return a + (-j) * (t - t_end4); + } + a += (-j) * profile.t5; + + if (t <= t_end6) { + return a; + } + + return a + j * (t - t_end6); +} + +double LgvSCurve::getJerkAtTime(const LgvSCurveProfile& profile, double t) const +{ + if (t <= 0.0 || t >= profile.total_time) { + return 0.0; + } + return computeSegmentJerk(profile, t); +} + +void LgvSCurve::generateTrajectory(const LgvSCurveProfile& profile, double dt, + std::vector& positions, + std::vector& velocities, + std::vector& accelerations) const +{ + positions.clear(); + velocities.clear(); + accelerations.clear(); + + if (profile.total_time <= 0 || dt <= 0) { + positions.push_back(profile.p0); + velocities.push_back(profile.v0); + accelerations.push_back(profile.a0); + return; + } + + int num_points = static_cast(std::ceil(profile.total_time / dt)) + 1; + positions.reserve(num_points); + velocities.reserve(num_points); + accelerations.reserve(num_points); + + for (double t = 0; t <= profile.total_time; t += dt) { + positions.push_back(getPositionAtTime(profile, t)); + velocities.push_back(getVelocityAtTime(profile, t)); + accelerations.push_back(getAccelerationAtTime(profile, t)); + } + + // 确保包含最终点 + if (positions.empty() || + std::abs(positions.back() - (profile.p0 + profile.distance * profile.direction)) > EPSILON) { + positions.push_back(profile.p0 + profile.distance * profile.direction); + velocities.push_back(profile.vf); + accelerations.push_back(0.0); + } +} + +double LgvSCurve::getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return profile.v0; + } + + if (t <= 0.0) { + return profile.v0; + } + if (t >= profile.total_time) { + return profile.vf; + } + + double v = profile.v0; + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + // seg1 + if (t <= profile.t1) { + process_segment(t, profile.j1); + return v; + } + process_segment(profile.t1, profile.j1); + + // seg2 + const double t_after_1 = t - profile.t1; + if (t_after_1 <= profile.t2) { + process_segment(t_after_1, profile.j2); + return v; + } + process_segment(profile.t2, profile.j2); + + // seg3 + const double t_after_2 = t_after_1 - profile.t2; + process_segment(t_after_2, profile.j3); + return v; +} + +double LgvSCurve::getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return profile.a0; + } + + if (t <= 0.0) { + return profile.a0; + } + if (t >= profile.total_time) { + return 0.0; + } + + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + a += jerk * dt; + }; + + // seg1 + if (t <= profile.t1) { + process_segment(t, profile.j1); + return a; + } + process_segment(profile.t1, profile.j1); + + // seg2 + const double t_after_1 = t - profile.t1; + if (t_after_1 <= profile.t2) { + process_segment(t_after_1, profile.j2); + return a; + } + process_segment(profile.t2, profile.j2); + + // seg3 + const double t_after_2 = t_after_1 - profile.t2; + process_segment(t_after_2, profile.j3); + return a; +} + +double LgvSCurve::getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return 0.0; + } + + if (t <= 0.0 || t >= profile.total_time) { + return 0.0; + } + + if (t <= profile.t1) { + return profile.j1; + } + if (t <= profile.t1 + profile.t2) { + return profile.j2; + } + return profile.j3; +} + +void LgvSCurve::integrateWholeProfile(const LgvSCurveVelocityProfile& profile, + double& v_end, + double& a_end) const +{ + double v = profile.v0; + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + process_segment(profile.t1, profile.j1); + process_segment(profile.t2, profile.j2); + process_segment(profile.t3, profile.j3); + + v_end = v; + a_end = a; +} + +bool LgvSCurve::isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const +{ + if (!profile.valid) { + return true; + } + + std::vector check_times; + check_times.reserve(8); + + check_times.push_back(0.0); + check_times.push_back(profile.t1); + check_times.push_back(profile.t1 + profile.t2); + check_times.push_back(profile.total_time); + + // seg1 内部若 acceleration 过零,则 velocity 可能在段内出现极值 + if (std::abs(profile.j1) > EPSILON && profile.t1 > EPSILON) { + const double tz = -profile.a0 / profile.j1; + if (tz > EPSILON && tz < profile.t1 - EPSILON) { + check_times.push_back(tz); + } + } + + for (double t : check_times) { + const double v = getVelocityAtTime(profile, t); + if (std::abs(v) > max_velocity_ + 1e-7) { + return false; + } + } + + return true; +} + +LgvSCurveVelocityProfile LgvSCurve::calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration) const +{ + LgvSCurveVelocityProfile best; + best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_); + best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_); + best.vf = clamp(end_velocity, -max_velocity_, max_velocity_); + + if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) { + // 退化情况:这里不做特殊退化规划,直接返回 invalid + return best; + } + + const double v0 = best.v0; + const double a0 = best.a0; + const double vf = best.vf; + + // 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0” + double s = sign(vf - v0); + if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) { + s = 1.0; + } + + const double dv = s * (vf - v0); // >= 0 + const double a0s = s * a0; // signed frame 下的初始 acceleration + const double j = max_jerk_; + const double amax = max_acceleration_; + + auto normalize_nonnegative = [](double x) { + return (x < 0.0 && x > -1e-10) ? 0.0 : x; + }; + + auto try_candidate = [&](double t1, double t2, double t3, + double j1s, double j2s, double j3s) { + t1 = normalize_nonnegative(t1); + t2 = normalize_nonnegative(t2); + t3 = normalize_nonnegative(t3); + + if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) { + return; + } + + LgvSCurveVelocityProfile cand; + cand.t1 = t1; + cand.t2 = t2; + cand.t3 = t3; + cand.total_time = t1 + t2 + t3; + + cand.j1 = s * j1s; + cand.j2 = s * j2s; + cand.j3 = s * j3s; + + cand.v0 = v0; + cand.a0 = a0; + cand.vf = vf; + cand.valid = true; + + double vend = 0.0; + double aend = 0.0; + integrateWholeProfile(cand, vend, aend); + + if (std::abs(vend - vf) > 1e-5) { + return; + } + if (std::abs(aend) > 1e-5) { + return; + } + if (!isVelocityLimitSatisfied(cand)) { + return; + } + + if (!best.valid || cand.total_time < best.total_time) { + best = cand; + } + }; + + // ---------------- UDU 三角形(无平台) ---------------- + { + // Δv = (2A^2 - a0^2)/(2j) + const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s); + if (A2 >= -1e-10) { + const double A = std::sqrt(std::max(0.0, A2)); + if (A <= amax + 1e-10 && A >= a0s - 1e-10) { + const double t1 = (A - a0s) / j; + const double t2 = 0.0; + const double t3 = A / j; + try_candidate(t1, t2, t3, +j, 0.0, -j); + } + } + } + + // ---------------- UDU 梯形(有平台) ---------------- + { + const double A = amax; + if (A > EPSILON && A >= a0s - 1e-10) { + const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j); + const double t1 = (A - a0s) / j; + const double t2 = (dv - base) / A; + const double t3 = A / j; + try_candidate(t1, t2, t3, +j, 0.0, -j); + } + } + + // ---------------- DUD 三角形(无平台) ---------------- + { + // Δv = (a0^2 - 2B^2)/(2j) + const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv); + if (B2 >= -1e-10) { + const double B = std::sqrt(std::max(0.0, B2)); + if (B <= amax + 1e-10 && B >= -a0s - 1e-10) { + const double t1 = (a0s + B) / j; + const double t2 = 0.0; + const double t3 = B / j; + try_candidate(t1, t2, t3, -j, 0.0, +j); + } + } + } + + // ---------------- DUD 梯形(有平台) ---------------- + { + const double B = amax; + if (B > EPSILON && B >= -a0s - 1e-10) { + const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j); + const double t1 = (a0s + B) / j; + const double t2 = (base - dv) / B; + const double t3 = B / j; + try_candidate(t1, t2, t3, -j, 0.0, +j); + } + } + + // 已到终点附近 + if (!best.valid && + std::abs(vf - v0) <= VELOCITY_THRESHOLD && + std::abs(a0) <= ACCELERATION_THRESHOLD) { + best.valid = false; + best.total_time = 0.0; + best.v0 = v0; + best.a0 = a0; + best.vf = vf; + } + + return best; +} + +void LgvSCurve::generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt, + std::vector& velocities, + std::vector& accelerations, + std::vector& jerks) const +{ + velocities.clear(); + accelerations.clear(); + jerks.clear(); + + if (!profile.valid || profile.total_time <= 0.0 || dt <= 0.0) { + velocities.push_back(profile.v0); + accelerations.push_back(profile.a0); + jerks.push_back(0.0); + return; + } + + const int num_points = static_cast(std::ceil(profile.total_time / dt)) + 1; + velocities.reserve(num_points); + accelerations.reserve(num_points); + jerks.reserve(num_points); + + for (double t = 0.0; t <= profile.total_time; t += dt) { + velocities.push_back(getVelocityAtTime(profile, t)); + accelerations.push_back(getAccelerationAtTime(profile, t)); + jerks.push_back(getJerkAtTime(profile, t)); + } + + if (velocities.empty() || std::abs(velocities.back() - profile.vf) > VELOCITY_THRESHOLD) { + velocities.push_back(profile.vf); + accelerations.push_back(0.0); + jerks.push_back(0.0); + } +} + +} // namespace cmvr diff --git a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt index a3270cd1..4ca9739b 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt +++ b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt @@ -1,5 +1,6 @@ add_library(motor_robot_arm SHARED src/motor_robot_arm.cpp + src/speed_l_executor.cpp ) target_include_directories(motor_robot_arm PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) @@ -8,10 +9,13 @@ target_link_libraries(motor_robot_arm PUBLIC cmvr_es::proto PRIVATE - cmvr_es::algorithms::arm_motion + cmvr_es::algorithms::lgv_arm_motion cmvr_es::ik_solver - cmvr_es::algorithms::arm_control + cmvr_es::joint_path_planner + cmvr_es::joint_trajectory_smoother + cmvr_es::collision_checker cmvr_es::device::motor_manager + cmvr_es::device::ethercat_motor_driver cmvr_es::device::mujoco_motor_driver glog ) @@ -19,11 +23,24 @@ target_link_libraries(motor_robot_arm add_library(cmvr_es::device::motor_robot_arm ALIAS motor_robot_arm) install(TARGETS motor_robot_arm LIBRARY DESTINATION lib) +add_executable(speed_l_executor_test src/speed_l_executor_test.cpp) +target_link_libraries(speed_l_executor_test PRIVATE + cmvr_es::device::motor_robot_arm gtest gtest_main pthread) + add_executable(speedl_reversal_mujoco_test src/speedl_reversal_mujoco_test.cpp) target_link_libraries(speedl_reversal_mujoco_test PRIVATE cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager cmvr_es::device::mujoco_motor_driver cmvr_es::proto pthread) +add_executable(rrt_connect_mujoco_test src/rrt_connect_mujoco_test.cpp) +target_compile_definitions(rrt_connect_mujoco_test PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(rrt_connect_mujoco_test PRIVATE + cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager + cmvr_es::ik_solver + cmvr_es::mujoco_world cmvr_es::mujoco_viewer + gtest gtest_main pthread) + add_executable(motor_robot_arm_mujoco_test src/motor_robot_arm_mujoco_test.cpp ) diff --git a/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md b/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md index 561872b9..e864f5d7 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md +++ b/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md @@ -1,12 +1,35 @@ # speedL 连续换向与 MuJoCo 验证 -触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。该模式下非同轴变向先停止再换轴;角速度仍使用原有策略。 +触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。非同轴转向使用三维速度过渡,保持速度与加速度连续,并检查整个过渡的速度、加速度、jerk 模长上界。非连续模式与角速度近反向时,仍先停稳再反向。 -`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,保持原有的小角度方向跟随和低速换轴行为;接近及回撤设为 true。固定轴模式不适合方向不断变化的视觉对齐:小方向变化会累积到换轴阈值,导致反复停走。设为 false 也可用于与旧换向策略做同条件比较。运动中退出固定轴模式时会保留实际运动方向和加速度。 +`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,接近及回撤设为 true。两种模式的非同轴转向都使用受限向量过渡,不再直接转动速度方向或累积小角度后周期性停车。连续旋转的 Tool 目标可能存在跟随滞后;受限规划不承诺瞬时到达新方向。运动中切换模式保留实际速度和加速度。旧换向余弦阈值与切轴速度阈值配置已删除。 -`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 仍可直接使用。控制线程将速度、加速度、jerk 作为同一命令读取。正常停止的收尾操作检查命令版本,避免清除之后提交的运动命令。 +`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 转发到这一入口。控制线程将速度、加速度、jerk 作为同一命令读取,新命令到达时原子更新限值和换向策略。运行中的新限值请求被拒绝时,执行器使用上一次有效参数提交一次零目标停止;恢复停止也失败才走直接零速收尾,并记录失败日志。`speedL()` 提交是异步的,周期线程里的拒绝通过日志报告。正常停止收尾和失败处理都检查命令版本,避免清除之后提交的运动命令。 -机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置或无效的上限继续使用规划器默认值(线性 0.55/5/10,角向 1/5/12)。 +`SpeedLExecutor` 位于 `devices/arm/motor_robot_arm`,由 `MotorRobotArm` 创建和持有,随机械臂停止、关闭或析构结束周期线程;Task 通过机械臂的 `speedL` / `stopL` 接口使用它,不管理执行器生命周期。配置中的 `speed_l_controller.cartesian_velocity_controller` 字段继续保持兼容。 + +调用职责:`MotorRobotArm` 检查机械臂状态并提供电机读写;`SpeedLExecutor` 管理命令、控制周期和停止;`PinocchioCartesianVelocityPlanner` 将平滑后的末端速度映射为关节速度并做限位、偏差检查;`SCurvePlanner` 管理方向及 S 曲线运行状态,`SCurve` 只做数学计算。执行器统一处理周期和停止阈值的默认值。 + +笛卡尔规划接口位于 `algorithms/planner/cartesian/`:`cartesian_trajectory_planner.h` 定义 MoveL 接口,独立的 `cartesian_velocity_planner.h` 定义 speedL 在线接口,`cartesian_motion_planner_factory.h` 提供工厂。Pinocchio 实现在其 `pinocchio/` 子目录,`SCurvePlanner` 在其 `s_curve/` 子目录;数学核心 `SCurve` 留在 `curves/s_curve/`。关节路径规划另放在 `algorithms/planner/joint/`。类名、职责与调用方式保持不变,库和测试目标仍由 `algorithms/planner/CMakeLists.txt` 统一定义,构建输出位置保持不变。 + +```cpp +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/cartesian_motion_planner_factory.h" +``` + +执行器只依赖 `CartesianVelocityPlanner` 在线接口,MoveL 接口保留在现有 `CartesianTrajectoryPlanner` 中。新命令调用一次 `submit(target, options, frame)`,每拍调用 `step(dt, q, qd)`;两者均由控制线程串行调用。`CartesianVelocityStep` 一次返回状态、关节速度命令、平滑后的 Base 目标 twist 和按需捕获的参考;失败时命令为空、twist 为零、参考无效。目标 twist 是关节限幅前的笛卡尔规划目标,不是实测 TCP 速度。旧的限值更新、独立捕获和规划器缓存 getter 接口已删除。 + +`PinocchioCartesianTrajectoryPlanner` 只实现 MoveL;`PinocchioCartesianVelocityPlanner` 只实现 speedL,独立持有在线目标和 SCurvePlanner。两个接口互不继承,`CartesianMotionPlannerFactory::createMoveL()` 和 `createSpeedL()` 分别创建并配置对应实例。两者共享机械臂的运动学求解器,机械臂切换到 MoveL 前先停止并等待速度控制线程退出。现有 protobuf 字段名保持兼容。 + +`SCurvePlanner` 初始化后每周期调用 `plan(target, frame, dt, base_R_tool)`;零目标表示平滑停止,相同目标继续已有曲线。`getAccelerationBase()` 是最终命令的区间平均加速度,`getJerkBase()` 按相邻区间中心时间差分,支持周期变化。没有反馈同步或独立停止状态入口。机械臂急停由 `MotorRobotArm` 关闭执行器并调用电机 quick stop。 + +`SCurvePlanner` 的限值必须为有限数且大于 1e-9,周期必须至少为 1e-9 秒,重规划阈值必须为有限非负数;非法初始速度、目标、周期、坐标系或 Tool 旋转矩阵中的非有限数会在修改状态前抛出 `std::invalid_argument`。Pinocchio 适配层把错误转为配置失败或 `InvalidArgument`。protobuf 限值与阈值为零时保留默认值,负数和非有限值拒绝。初始化速度超过上限会拒绝,不能只截断内部标量。动态降低限值时,若当前速度、加速度已超过新上限,或无法验证后续曲线满足新上限,拒绝更新并保留完整旧状态;不直接截断当前速度、加速度。标量曲线计算无解或产生非有限结果时抛出 `std::runtime_error`,适配层返回 `CommandFailed`。方向过渡候选未通过时继续推进已经验证的原曲线,再尝试新目标,不会冻结当前非零加速度。 + +参考捕获使用首次成功 `step` 的 TCP 位姿,Tool 目标由规划器锁定为该拍的 Base 方向;后续周期不重新旋转这一已锁定目标。执行器只在电机发送成功且命令版本仍匹配时发布参考。未请求捕获的 Tool 目标仍随每拍 Tool 坐标系转换。发送回调只接收关节速度,不再传递已由规划器处理的加速度。 + +每个规划周期合并计算当前 TCP 位姿和 Jacobian,当前直线偏差检查复用该位姿。启用直线偏差检查且正在平移时,仍单独计算预测下一周期的 FK 并复检。执行器复用关节状态和输出缓冲区。 + +机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置的上限使用规划器默认值(线性 0.55/5/10,角向 1/5/12),非法数值明确拒绝。 例如机械臂配置加速度 5、jerk 10 时,回撤请求 60/60 实际按 5/10 规划,请求 3/6 则按 3/6 规划。任务参数不能提高机械臂上限。 @@ -36,29 +59,33 @@ touch { 先 MoveJ 到已有运动测试姿态,然后调用 `speedL(vy=+0.08)`,运动过程中直接调用 `speedL(vy=-0.08)`。默认 Base 坐标系,`--tool-frame true` 可验证 Tool 坐标系。测量来自 MuJoCo `R_FINGER_TIP_SITE` 的位置和雅可比乘实际 qvel;不是规划速度的积分。 -在仓库根目录运行(需要已配置 `cmake-build-debug`;可用 `CMVR_BUILD_DIR` 覆盖): +在仓库根目录先完成构建和安装,再直接运行测试程序: ```bash +./scripts/build.sh Debug +export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +speedl_test="$PWD/build/Debug/cmvr-es/devices/arm/motor_robot_arm/speedl_reversal_mujoco_test" + # 匀速阶段换向:接近加速度 5,回撤加速度 3,jerk 均为 10。 -./script/test_speedl_reversal_mujoco.sh --csv /tmp/reversal-new.csv +"$speedl_test" --csv /tmp/reversal-new.csv # 同一新版本中选择旧换向策略,比较算法本身。 -./script/test_speedl_reversal_mujoco.sh --legacy true --csv /tmp/reversal-legacy.csv +"$speedl_test" --legacy true --csv /tmp/reversal-legacy.csv # 仍在加速时,命令 vy 首次达到 0.032 m/s 即反向。 -./script/test_speedl_reversal_mujoco.sh --trigger-speed 0.032 --csv /tmp/reversal-accelerating.csv +"$speedl_test" --trigger-speed 0.032 --csv /tmp/reversal-accelerating.csv # 上限仍为 10,回撤请求 60 将被限制为 10。 -./script/test_speedl_reversal_mujoco.sh --reverse-jerk 60 --reverse-acceleration 60 \ +"$speedl_test" --reverse-jerk 60 --reverse-acceleration 60 \ --capture-reference true --csv /tmp/reversal-capped.csv # 将仿真机械臂 jerk 上限设为 60;接近请求 10,回撤请求 60。 -./script/test_speedl_reversal_mujoco.sh --jerk 60 --approach-jerk 10 \ +"$speedl_test" --jerk 60 --approach-jerk 10 \ --reverse-jerk 60 --capture-reference true \ --csv /tmp/reversal-jerk60.csv # Tool 坐标系和触屏任务使用的参数接口。 -./script/test_speedl_reversal_mujoco.sh --tool-frame true --jerk 60 --approach-jerk 10 --reverse-jerk 60 \ +"$speedl_test" --tool-frame true --jerk 60 --approach-jerk 10 --reverse-jerk 60 \ --capture-reference true --csv /tmp/reversal-tool.csv ``` @@ -66,14 +93,16 @@ touch { `max_forward_mm` 是反向调用前采样点之后,实际 TCP 沿前进轴的最大正位移;`peak_at_ms` 是到达该最远点的时间;`actual_reverse_ms` 要求至少连续 5 次采样的轴向速度小于 -0.0001 m/s;`return_to_origin_ms` 是确认反向后返回调用时位置的时间。Tool 模式的 CSV 速度字段也表示沿锁定前进轴的投影。 -测试要求换向前实际速度为正、之后产生反向速度并退回起点,且控制器未提前退出;使用起点锁存时还要求参考有效。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。 +测试要求换向前实际速度为正、之后产生反向速度并退回起点,且执行器未提前退出;使用起点锁存时还要求参考有效。停止后要求执行器退出 busy、TCP 实测线速度低于 0.01 m/s,再依次执行 `moveL`、恢复 `speedL`、停止和 `moveJ`,验证模式切换。`MODE_SWITCH` 日志记录 MoveL 位置误差、恢复运动的实际位移和停止残速。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。 + +现有 `motor_robot_arm_mujoco_test` 默认打开可视化窗口;设置 `CMVR_MUJOCO_HEADLESS=1` 可在不创建窗口的情况下运行相同的 MoveJ、MoveL 和 speedL 仿真检查。 ## 回归测试 -构建并运行 `cartesian_twist_limiter_reversal_test`、`s_curve_velocity_planner_stop_test` 和 `cartesian_velocity_controller_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、普通停止、非同轴转向、负速度反馈、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。 +构建并运行 `s_curve_planner_reversal_test` 和 `speed_l_executor_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、重复零目标平滑停止、非同轴转向、负速度下切换策略、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。 -`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、旧接口及停止、独立角加速度限幅和非法请求。测试不初始化电机。 +`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、仅指定加速度及停止、独立角加速度限幅和非法请求。另验证未提交命令及单步失败时不返回旧输出,以及 Tool 参考锁定后与 Base 目标的持续输出一致。测试不初始化电机。 -对齐回归覆盖每 20 ms 小幅更新速度方向:显式关闭固定轴模式后,20 mm/s 的命令不会因方向变化反复降到零;同时验证对齐后启用连续换向仍能平滑过零,以及反向运动中退出固定轴模式不会翻转实际速度。 +对齐回归覆盖每 20 ms 小幅更新方向、单拍 0.01 rad 方向变化、持续旋转 Tool 目标和速度恰在上限的情况,直接对最终速度命令差分检查 a/j 模长,并验证没有周期性降零。另覆盖拒绝不兼容降限后未来轨迹不变、角限值失败不部分更新线限值,以及停止恢复只重试一次。同轴连续换向过零仍保留加速度。 -运行时应优先加载当前构建的项目动态库,测试脚本已处理;不要把新可执行文件与 `output/lib` 的旧项目库混用。 +运行前应确认构建和安装成功,确保 `output/lib` 中的项目动态库与测试程序属于同一次构建。 diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h index 6ddb1734..1c869866 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h +++ b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h @@ -2,6 +2,7 @@ #define CMVR_ES_MOTOR_ROBOT_ARM_H #include +#include #include #include #include @@ -9,14 +10,19 @@ #include #include -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h" -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" +#include "algorithms/smoother/joint_trajectory_smoother.h" +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" #include "cmvr/config/arm_config/arm_config.pb.h" #include "devices/arm/robot_arm.h" #include "algorithms/kinematics/ik_solver/common/include/ik_solver.h" #include "motor/manager/include/motor_manager.h" +namespace cmvr { +class JointPathPlanner; +class CollisionChecker; +} + namespace cmvr::device { class MotorRobotArm final : public RobotArm { @@ -33,7 +39,9 @@ public: ArmState getRobotState() const override; JointGroupState getJointState() const override; CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override; - RobotMode getRobotMode() const override { return RobotMode::Idle; } + RobotMode getRobotMode() const override { + return isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle); + } SafetyMode getSafetyMode() const override; ControlMode getControlMode() const override { return ControlMode::Position; } @@ -46,10 +54,10 @@ public: const JointTrajectory& path, const MotionOptions& options) override; Result setSpeedScaling(double scaling) override; - double getSpeedScaling() const override { return speed_scaling_; } + double getSpeedScaling() const override { return speed_scaling_.load(); } bool isProtectiveStopped() const override { return protective_stopped_.load(); } bool isEmergencyStopped() const override { return emergency_stopped_.load(); } - bool isFault() const override { return false; } + bool isFault() const override; Result moveJ(const JointPositionCommand& target, const MotionOptions& options) override; Result speedJ(const JointVelocityCommand& velocity, double acceleration, double duration) override; @@ -57,6 +65,14 @@ public: Result moveL(const CartesianPose& target, const MotionOptions& options, FrameType frame = FrameType::Base) override; + // IK -> RRTConnect -> quintic B-spline -> cyclic position commands. + // Synchronous; Base is absolute, Tool is relative to the current TCP. + // Joint velocity/acceleration/jerk limits use rad/s, rad/s², rad/s³. + Result moveP(const CartesianPose& target, + const MotionOptions& options, + FrameType frame = FrameType::Base) override; + Result moveP(const JointPositionCommand& target, + const MotionOptions& options) override; Result speedL(const CartesianVelocity& velocity, double acceleration, double duration, @@ -65,6 +81,7 @@ public: Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, double duration, FrameType frame = FrameType::Base) override; SpeedLReference getSpeedLReference() const override; + Result getSpeedLResult() const override; Result stopMotion() override; Result startServoMode(const ServoOptions& options) override; @@ -81,7 +98,8 @@ public: Result powerOff() override { return torqueOff(); } Result brakeRelease() override; Result shutdown() override; - Result clearFault() override { return Result::success(); } + Result clearFault() override; + Result recoverSpeedLPlanningFault() override; Result unlockProtectiveStop() override; Result loadProgram(const std::string& program_name) override; Result playProgram() override; @@ -104,18 +122,32 @@ private: std::optional safetyStopResult_(const std::string& command, bool interrupted = false) const; Result quickStopMotors_(); + // Already scaled/planned velocities; never apply speed_scaling_ here. + Result sendJointVelocity_(const JointVelocityCommand& velocity); bool validatePositionCommand_(const JointPositionCommand& cmd, std::string& error) const; bool validateVelocityCommand_(const JointVelocityCommand& cmd, std::string& error) const; std::shared_ptr getMotor_(const std::string& joint_name) const; bool readArmState_(std::vector& q_now, std::vector& qd_now) const; std::vector readJointPosition_() const; Result stopCartesianMotionAndWait_(); - Result waitForJointTarget_(const std::vector& target) const; + // Resolve the goal from the stopped start state while holding mutex_, then + // share path planning, smoothing, validation and execution for both targets. + Result planAndExecuteJointPath_( + const MotionOptions& options, + const std::function&, std::vector&)>& resolve_goal); + Result waitForJointTarget_(const std::vector& target, + const std::function& is_cancelled = {}, + const std::string& command = "moveJ") const; + bool planRecoveryTrajectory_(const std::vector& current_position, + const JointTrajectory& recorded_trajectory, + const MotionOptions& options, + JointTrajectory& replay_trajectory) const; bool configureAlgorithms_(); + bool configureJointPathPlanner_(); bool executeMoveLTrajectory_(const CartesianJointTrajectory& trajectory); - static CartesianVelocityController::Config toCartesianVelocityControllerConfig_( + static SpeedLExecutor::Config toSpeedLExecutorConfig_( const config::CartesianVelocityControllerConfig& config); std::vector moveLJointVelocityLimits_(const std::vector& qd_max) const; static Result unsupported_(const std::string& name); @@ -131,12 +163,16 @@ private: std::shared_ptr motor_manager_{nullptr}; std::shared_ptr ik_solver_{nullptr}; - std::shared_ptr joint_planner_{nullptr}; - std::shared_ptr cartesian_planner_{nullptr}; - std::unique_ptr cartesian_velocity_controller_{nullptr}; + std::shared_ptr trajectory_smoother_; + std::shared_ptr joint_path_planner_; + std::unique_ptr path_collision_checker_; + double joint_trajectory_sample_period_s_{0.001}; + std::shared_ptr cartesian_planner_{nullptr}; + std::unique_ptr speed_l_executor_{nullptr}; - // MoveJ post-trajectory settling criteria. These defaults preserve the + // Joint-motion position-limit tolerance and post-trajectory settling criteria. These defaults preserve the // historical behavior when the optional arm configuration fields are absent. + double move_j_joint_limit_tolerance_rad_{1e-5}; double move_j_settle_timeout_s_{2.0}; double move_j_position_tolerance_rad_{2e-3}; double move_j_velocity_tolerance_rad_s_{2e-2}; @@ -144,8 +180,8 @@ private: mutable std::mutex mutex_; std::atomic busy_{false}; - std::atomic powered_on_{false}; - double speed_scaling_{1.0}; + std::atomic joint_motion_stop_generation_{0}; + std::atomic speed_scaling_{1.0}; std::atomic protective_stopped_{false}; std::atomic emergency_stopped_{false}; std::atomic protective_recovery_active_{false}; diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h b/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h new file mode 100644 index 00000000..09a6127f --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h @@ -0,0 +1,119 @@ +#ifndef CMVR_ES_SPEED_L_EXECUTOR_H +#define CMVR_ES_SPEED_L_EXECUTOR_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +class SpeedLExecutor { +public: + struct Config { + double control_period_s{0.001}; + double stop_twist_norm{1e-9}; + double stop_command_velocity_norm{1e-3}; + double stop_measured_velocity_norm{1e-2}; + double stop_acceleration{0.5}; + double stop_timeout_s{2.0}; + }; + + using ReadStateCallback = std::function& q, std::vector& qd)>; + using SendVelocityCallback = std::function; + using ReadScalingCallback = std::function; + // Optional external clock: begin waits for a cycle and returns its period; + // end releases it, including when planning or I/O fails. + using BeginCycleCallback = std::function; + using EndCycleCallback = std::function; + + SpeedLExecutor(Config config, + std::shared_ptr planner, + std::size_t dof, + ReadStateCallback read_state, + SendVelocityCallback send_velocity, + ReadScalingCallback read_scaling = {}, + BeginCycleCallback begin_cycle = {}, + EndCycleCallback end_cycle = {}); + ~SpeedLExecutor(); + + SpeedLExecutor(const SpeedLExecutor&) = delete; + SpeedLExecutor& operator=(const SpeedLExecutor&) = delete; + + Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, + double duration, FrameType frame); + Result stop(std::optional acceleration = std::nullopt); + SpeedLReference getReference() const; + // Reports whether zero output and stationary feedback were confirmed. + // Earlier asynchronous errors remain available through lastResult(). + Result shutdown(); + Result lastResult() const; + bool faulted() const { return faulted_.load(); } + Result clearFault(); + // Automatic recovery is limited to planning failures with no I/O or stop + // failure. A fresh zero command and stationary feedback are required. + Result clearPlanningFault(); + // Include failures from arm-level stopping performed outside this worker. + void recordStopFailure(const Result& result); + + bool busy() const { return busy_.load(); } + double stopTimeoutS() const { return config_.stop_timeout_s; } + CartesianVelocity getCommandTwistBase() const; + +private: + void workerLoop_(); + void setStopTargetLocked_(double acceleration); + Result finish_(); + Result readState_(std::vector& q, std::vector& qd) const; + Result sendVelocity_(const JointVelocityCommand& velocity) const; + Result clearFault_(bool planning_only); + void recordFailureLocked_(const Result& result, bool planning_failure = false); + void finishCommand_(); + + static double velocityNorm_(const std::vector& velocity); + static double twistNorm_(const CartesianVelocity& velocity); + +private: + Config config_; + std::shared_ptr planner_; + std::size_t dof_{0}; + ReadStateCallback read_state_; + SendVelocityCallback send_velocity_; + ReadScalingCallback read_scaling_; + BeginCycleCallback begin_cycle_; + EndCycleCallback end_cycle_; + + std::thread worker_; + std::mutex lifecycle_mutex_; + mutable std::mutex mutex_; + std::condition_variable cv_; + std::atomic stop_requested_{false}; + bool command_active_{false}; + bool finishing_{false}; + bool reset_required_{true}; + CartesianVelocity target_twist_{}; + FrameType target_frame_{FrameType::Base}; + SpeedLOptions target_options_{}; + SpeedLReference reference_{}; + CartesianVelocity command_twist_snapshot_{}; + std::uint64_t command_version_{0}; + std::atomic busy_{false}; + std::atomic faulted_{false}; + bool planning_fault_{false}; + Result pending_stop_reason_{Result::success()}; + Result last_result_{Result::success()}; + Result shutdown_result_{Result::success()}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_SPEED_L_EXECUTOR_H diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp index 7fbfb810..39007c18 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp @@ -5,20 +5,27 @@ #include #include #include +#include #include #include #include -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h" +#include "algorithms/planner/cartesian/cartesian_motion_planner_factory.h" +#include "algorithms/smoother/joint_trajectory_smoother_factory.h" +#include "algorithms/smoother/joint_trajectory_validation.h" +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "algorithms/collision_detection/include/collision_checker.h" #include "algorithms/kinematics/ik_solver/ik_solver_factory.h" #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" #include "common/base/protobuf_utils.h" +#include "common/config/config_files.h" #include "common/base/string_utils.h" #include "common/base/logging/logger.h" #include "common/math/transform_math.h" #include "motor/abstract_motor.h" +#include "motor/drivers/ethercat_motor/include/ethercat_motor.h" #include "motor/manager/include/motor_manager.h" +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" namespace cmvr::device { @@ -78,8 +85,8 @@ MotorRobotArm::MotorRobotArm(const config::RobotArmConfig& cfg) MotorRobotArm::~MotorRobotArm() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); + if (speed_l_executor_) { + speed_l_executor_->shutdown(); } } @@ -129,6 +136,17 @@ bool MotorRobotArm::init() CMVR_LOG(ERROR) << "[MotorRobotArm] failed to configure algorithms: " << id_; return false; } + // Choose the arm's initial position-control mode before enabling any axis. + for (const auto& joint_name : joint_names_) { + const auto motor = motor_manager_->getMotor(joint_name); + if (std::dynamic_pointer_cast(motor) && + motor->getMode() == msgs::RUN_MODE_UNSPECIFIED && + !motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION)) { + CMVR_LOG(ERROR) << "[MotorRobotArm] failed to configure initial motor mode: " + << joint_name; + return false; + } + } CMVR_LOG(INFO) << "[MotorRobotArm] (init): Arm '" << id_ << "' init success"; return true; } @@ -144,36 +162,62 @@ ArmState MotorRobotArm::getRobotState() const const bool emergency_stopped = emergency_stopped_.load(); ArmState state; state.connected = motor_manager_ != nullptr; - state.powered_on = powered_on_.load(); - state.brake_released = powered_on_.load() && !emergency_stopped; + state.powered_on = true; + state.brake_released = !emergency_stopped; state.moving = busy(); state.protective_stopped = protective_stopped; state.emergency_stopped = emergency_stopped; - state.speed_scaling = speed_scaling_; - state.robot_mode = RobotMode::Idle; + state.speed_scaling = speed_scaling_.load(); + state.robot_mode = getRobotMode(); + state.fault = isFault(); state.safety_mode = getSafetyMode(); state.control_mode = ControlMode::Position; state.actual_joint_state = getJointState(); - state.actual_tcp_pose = getTcpPose(); - state.actual_tcp_velocity = getSpeedLCommandTwistBase(); + const auto& q = state.actual_joint_state.position; + const auto& qd = state.actual_joint_state.velocity; + if (q.size() != getDof() || qd.size() != getDof() || + !std::all_of(q.begin(), q.end(), [](double v) { return std::isfinite(v); }) || + !std::all_of(qd.begin(), qd.end(), [](double v) { return std::isfinite(v); })) { + state.fault = true; + state.robot_mode = RobotMode::Fault; + return state; + } + if (!ik_solver_) { + return state; + } + auto solver = std::dynamic_pointer_cast(ik_solver_); + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (solver && solver->computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)) { + state.actual_tcp_pose = common::math::matrixToPose(pose); + const Eigen::Matrix twist = jacobian * + Eigen::Map(qd.data(), static_cast(qd.size())); + state.actual_tcp_velocity = common::math::vectorToVelocity(twist); + } else { + state.fault = true; + state.robot_mode = RobotMode::Fault; + } return state; } JointGroupState MotorRobotArm::getJointState() const { JointGroupState state; - state.position.reserve(joint_names_.size()); - state.velocity.reserve(joint_names_.size()); - state.effort.reserve(joint_names_.size()); - state.current.reserve(joint_names_.size()); + std::vector> motors; + motors.reserve(joint_names_.size()); for (const auto& joint_name : joint_names_) { auto motor = getMotor_(joint_name); if (!motor) { - continue; + return state; } - state.position.push_back(motor->getQ()); - state.velocity.push_back(motor->getQd()); - state.effort.push_back(0.0); + motors.push_back(std::move(motor)); + } + if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity)) + return {}; + state.effort.assign(motors.size(), 0.0); + state.current.reserve(motors.size()); + for (const auto& motor : motors) { state.current.push_back(static_cast(motor->getCurrent())); } return state; @@ -190,8 +234,11 @@ CartesianPose MotorRobotArm::getTcpPose(const FrameType frame) const if (!readArmState_(q_now, qd_now)) { return {}; } - Eigen::Matrix4d transform = Eigen::Matrix4d::Identity(); - if (!ik_solver_->fk(q_now, transform, true)) { + auto solver = std::dynamic_pointer_cast(ik_solver_); + Eigen::Matrix4d transform; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver || !solver->computePoseAndJacobianBaseAtQ(q_now, true, transform, jacobian, rotation)) { return {}; } return common::math::matrixToPose(transform); @@ -205,7 +252,7 @@ SafetyMode MotorRobotArm::getSafetyMode() const if (protective_stopped_.load()) { return SafetyMode::ProtectiveStop; } - return SafetyMode::Normal; + return isFault() ? SafetyMode::Fault : SafetyMode::Normal; } Result MotorRobotArm::torqueOn() @@ -221,7 +268,6 @@ Result MotorRobotArm::torqueOn() } } emergency_stopped_.store(false); - powered_on_.store(true); return Result::success(); } @@ -237,7 +283,6 @@ Result MotorRobotArm::torqueOff() "failed to torque off motor for joint: " + joint_name); } } - powered_on_.store(false); return Result::success(); } @@ -273,13 +318,12 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name) Result MotorRobotArm::emergencyStop() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); - } protective_recovery_cancel_requested_.store(true); protective_stopped_.store(false); emergency_stopped_.store(true); - return quickStopMotors_(); + const auto stopped = quickStopMotors_(); + const auto joined = speed_l_executor_ ? speed_l_executor_->shutdown() : Result::success(); + return stopped.ok() ? joined : stopped; } Result MotorRobotArm::protectiveStop() @@ -287,14 +331,168 @@ Result MotorRobotArm::protectiveStop() if (emergency_stopped_.load()) { return Result::success(); } - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); - } protective_recovery_cancel_requested_.store(true); protective_stopped_.store(true); - return quickStopMotors_(); + const auto stopped = quickStopMotors_(); + const auto joined = speed_l_executor_ ? speed_l_executor_->shutdown() : Result::success(); + return stopped.ok() ? joined : stopped; } +bool MotorRobotArm::planRecoveryTrajectory_( + const std::vector& current_position, + const JointTrajectory& recorded_trajectory, + const MotionOptions& options, + JointTrajectory& replay_trajectory) const +{ + replay_trajectory.clear(); + if (current_position.empty() || recorded_trajectory.size() < 2 || + options.velocity <= 0.0 || + options.acceleration <= 0.0 || !std::isfinite(options.velocity) || + !std::isfinite(options.acceleration)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid trajectory or options"; + return false; + } + + const std::size_t dof = current_position.size(); + if (!options.joint_velocity_limits.empty() && + options.joint_velocity_limits.size() != dof) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid DOF or joint limits"; + return false; + } + for (const double position : current_position) { + if (!std::isfinite(position)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] non-finite current position"; + return false; + } + } + for (std::size_t i = 0; i < recorded_trajectory.size(); ++i) { + const auto& point = recorded_trajectory[i]; + if (!std::isfinite(point.time_s) || point.position.size() != dof || + (i > 0 && point.time_s <= recorded_trajectory[i - 1].time_s)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid recorded point: " + << i; + return false; + } + for (std::size_t joint = 0; joint < dof; ++joint) { + if (!std::isfinite(point.position[joint])) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] non-finite recorded point: " + << i; + return false; + } + } + } + + std::vector velocity_limits = options.joint_velocity_limits; + if (velocity_limits.empty()) { + velocity_limits.assign(dof, options.velocity); + } + for (std::size_t joint = 0; joint < velocity_limits.size(); ++joint) { + const double limit = velocity_limits[joint]; + if (!std::isfinite(limit) || limit <= 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid joint velocity limit"; + return false; + } + } + + const double ramp_duration_s = std::max( + joint_trajectory_sample_period_s_, options.velocity / options.acceleration); + replay_trajectory.reserve(recorded_trajectory.size() + 2); + replay_trajectory.push_back(JointTrajectoryPoint{ + 0.0, current_position, std::vector(dof, 0.0)}); + + double replay_time_s = ramp_duration_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory.back().position, + std::vector(dof, 0.0)}); + for (std::size_t i = recorded_trajectory.size() - 1; i > 0; --i) { + replay_time_s += recorded_trajectory[i].time_s - + recorded_trajectory[i - 1].time_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory[i - 1].position, + std::vector(dof, 0.0)}); + } + replay_time_s += ramp_duration_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory.front().position, + std::vector(dof, 0.0)}); + + const auto update_velocities = [&] { + for (auto& point : replay_trajectory) { + std::fill(point.velocity.begin(), point.velocity.end(), 0.0); + } + for (std::size_t i = 1; i + 1 < replay_trajectory.size(); ++i) { + const double dt = replay_trajectory[i + 1].time_s - + replay_trajectory[i - 1].time_s; + for (std::size_t joint = 0; joint < dof; ++joint) { + replay_trajectory[i].velocity[joint] = + (replay_trajectory[i + 1].position[joint] - + replay_trajectory[i - 1].position[joint]) / dt; + } + } + }; + + for (int iteration = 0; iteration < 3; ++iteration) { + update_velocities(); + double required_scale = 1.0; + std::vector previous_position_velocity(dof, 0.0); + for (std::size_t i = 0; i < replay_trajectory.size(); ++i) { + const auto& point = replay_trajectory[i]; + for (std::size_t joint = 0; joint < dof; ++joint) { + required_scale = std::max( + required_scale, + std::abs(point.velocity[joint]) / velocity_limits[joint]); + if (i == 0) { + continue; + } + + const double dt = point.time_s - + replay_trajectory[i - 1].time_s; + const double position_velocity = + (point.position[joint] - + replay_trajectory[i - 1].position[joint]) / dt; + const double acceleration = + (point.velocity[joint] - + replay_trajectory[i - 1].velocity[joint]) / dt; + required_scale = std::max( + required_scale, + std::abs(position_velocity) / velocity_limits[joint]); + required_scale = std::max( + required_scale, + std::sqrt(std::abs(acceleration) / + options.acceleration)); + if (i > 1) { + const double position_acceleration = + (position_velocity - + previous_position_velocity[joint]) / dt; + required_scale = std::max( + required_scale, + std::sqrt(std::abs(position_acceleration) / + options.acceleration)); + } + previous_position_velocity[joint] = position_velocity; + } + } + + if (required_scale <= 1.0 + 1e-9) { + break; + } + required_scale *= 1.001; + for (auto& point : replay_trajectory) { + point.time_s *= required_scale; + } + } + update_velocities(); + if (!validateJointTrajectory(replay_trajectory, dof, options)) { + replay_trajectory.clear(); + return false; + } + return true; +} + + Result MotorRobotArm::recoverProtectiveStop( const JointTrajectory& path, const MotionOptions& options) @@ -353,15 +551,9 @@ Result MotorRobotArm::recoverProtectiveStop( AtomicFlagGuard recovery_guard{protective_recovery_active_}; protective_recovery_cancel_requested_.store(false); - if (!joint_planner_) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "protective recovery planner is not initialized"); - } - JointTrajectory recovery_trajectory; const auto planning_start = std::chrono::steady_clock::now(); - if (!joint_planner_->planReplay( + if (!planRecoveryTrajectory_( readJointPosition_(), path, options, recovery_trajectory)) { return Result::failure( ArmErrorCode::CommandFailed, @@ -464,17 +656,19 @@ Result MotorRobotArm::unlockProtectiveStop() Result MotorRobotArm::quickStopMotors_() { + Result result = Result::success(); for (const auto& joint_name : joint_names_) { auto motor = getMotor_(joint_name); if (!motor) { - return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name); + if (result.ok()) result = Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name); + continue; } if (!motor->quickStop()) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to quick stop motor for joint: " + joint_name); + if (result.ok()) result = Result::failure(ArmErrorCode::CommandFailed, + "failed to quick stop motor for joint: " + joint_name); } } - return Result::success(); + return result; } bool MotorRobotArm::safetyStopRequested_() const @@ -502,15 +696,16 @@ std::optional MotorRobotArm::safetyStopResult_( Result MotorRobotArm::setSpeedScaling(const double scaling) { - if (scaling < 0.0 || scaling > 1.0) { + if (!std::isfinite(scaling) || scaling < 0.0 || scaling > 1.0) { return Result::failure(ArmErrorCode::InvalidArgument, "speed scaling must be in [0, 1]"); } - speed_scaling_ = scaling; + speed_scaling_.store(scaling); return Result::success(); } Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOptions& options) { + const auto stop_generation = joint_motion_stop_generation_.load(); if (const auto stopped = safetyStopResult_("moveJ")) { return *stopped; } @@ -518,11 +713,11 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti if (!validatePositionCommand_(target, error)) { return Result::failure(ArmErrorCode::InvalidArgument, error); } - if (!joint_planner_) { - return Result::failure(ArmErrorCode::RobotNotReady, "joint planner is not initialized"); + if (!trajectory_smoother_) { + return Result::failure(ArmErrorCode::RobotNotReady, "joint trajectory smoother is not initialized"); } - // speedL runs in a worker thread and sends speedJ commands. A moveJ + // speedL runs in a worker thread and sends joint velocity commands. A moveJ // trajectory writes cyclic-position commands directly, so allowing both // paths to run concurrently can overwrite the motor mode/target and cause // a short surge at the transition. Finish the Cartesian worker before @@ -537,14 +732,108 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti BusyGuard busy_guard{busy_}; std::lock_guard lock(mutex_); + Eigen::VectorXd lower, upper, joint_velocity; + if (ik_solver_) { + if (!ik_solver_->getJointPositionLimits(lower, upper) || + !ik_solver_->getJointVelocityLimits(joint_velocity) || + lower.size() != dof_ || upper.size() != dof_ || joint_velocity.size() != dof_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveJ cannot read joint limits"); + } + } else if (model_.joint_limits.size() == getDof()) { + lower.resize(dof_); + upper.resize(dof_); + joint_velocity.resize(dof_); + for (std::size_t j = 0; j < getDof(); ++j) { + lower[j] = model_.joint_limits[j].lower; + upper[j] = model_.joint_limits[j].upper; + joint_velocity[j] = model_.joint_limits[j].max_velocity; + } + } else { + return Result::failure(ArmErrorCode::RobotNotReady, "moveJ cannot read joint limits"); + } + MotionOptions limits = options; + if (!options.joint_velocity_limits.empty() && options.joint_velocity_limits.size() != getDof()) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveJ joint velocity limit count does not match DOF"); + } + limits.joint_velocity_limits.resize(getDof()); + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(joint_velocity[j]) || joint_velocity[j] <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint velocity limit"); + } + double velocity = joint_velocity[j]; + if (!options.joint_velocity_limits.empty()) { + const double requested = options.joint_velocity_limits[j]; + if (!std::isfinite(requested) || requested <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveJ joint velocity limit"); + } + velocity = std::min(velocity, requested); + } + limits.joint_velocity_limits[j] = std::min(options.velocity, velocity); + if (!ik_solver_ && model_.joint_limits[j].max_acceleration > 0.0) { + limits.acceleration = std::min(limits.acceleration, + model_.joint_limits[j].max_acceleration); + } + } + const double scaling = speed_scaling_.load(); + if (!std::isfinite(scaling) || scaling <= 0.0 || scaling > 1.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveJ speed scaling"); + } + limits.velocity *= scaling; + for (auto& velocity : limits.joint_velocity_limits) velocity *= scaling; + const auto cancelled = [&] { + return safetyStopRequested_() || joint_motion_stop_generation_.load() != stop_generation || + (options.cancellation_requested && options.cancellation_requested()); + }; + limits.cancellation_requested = cancelled; JointTrajectory samples; - if (!joint_planner_->planMoveJ(readJointPosition_(), target, options, speed_scaling_, samples)) { - return Result::failure(ArmErrorCode::CommandFailed, "[MotorRobotArm] moveJ planner failed: " + id_); + if (!trajectory_smoother_->smooth({readJointPosition_(), target.position}, limits, + joint_trajectory_sample_period_s_, samples)) { + if (const auto stopped = safetyStopResult_("moveJ", true)) return *stopped; + if (cancelled()) return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + return Result::failure(ArmErrorCode::CommandFailed, "[MotorRobotArm] moveJ smoothing failed: " + id_); } if (samples.size() < 2) { return Result::success(); } + if (!validateJointTrajectory(samples, getDof(), limits)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ B-spline violates motion limits"); + } + // Preserve the configured position tolerance, including the measured start. + for (const auto& sample : samples) { + if (sample.position.size() != getDof()) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ sample size mismatch"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + const double position = sample.position[j]; + if (!std::isfinite(position) || position < lower[j] - move_j_joint_limit_tolerance_rad_ || + position > upper[j] + move_j_joint_limit_tolerance_rad_) { + std::ostringstream message; + message << std::setprecision(12) + << "moveJ B-spline trajectory exceeds joint limits: arm=" << id_ + << ", joint=" << joint_names_[j] << ", time_s=" << sample.time_s + << ", position_rad=" << position << ", lower_rad=" << lower[j] + << ", upper_rad=" << upper[j] + << ", tolerance_rad=" << move_j_joint_limit_tolerance_rad_; + CMVR_LOG(ERROR) << "[MotorRobotArm] " << message.str(); + return Result::failure(ArmErrorCode::CommandFailed, message.str()); + } + } + } + + if (options.trajectory_callback) { + try { + options.trajectory_callback(samples); + } catch (const std::exception& e) { + return Result::failure(ArmErrorCode::CommandFailed, + std::string("moveJ trajectory callback failed: ") + e.what()); + } catch (...) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ trajectory callback failed"); + } + } + if (cancelled()) { + return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + } std::vector> motors; motors.reserve(joint_names_.size()); for (const auto& joint_name : joint_names_) { @@ -563,13 +852,18 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti } const auto t0 = std::chrono::steady_clock::now(); - constexpr double fallback_dt = 0.001; std::vector command_velocity(motors.size(), 0.0); for (std::size_t k = 1; k < samples.size(); ++k) { + const auto& sample = samples[k]; + std::this_thread::sleep_until(t0 + std::chrono::duration_cast( + std::chrono::duration(sample.time_s))); if (const auto stopped = safetyStopResult_("moveJ", true)) { return *stopped; } - const auto& sample = samples[k]; + if (cancelled()) { + quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + } if (sample.position.size() != motors.size()) { return Result::failure(ArmErrorCode::CommandFailed, "moveJ sample size mismatch"); } @@ -587,13 +881,6 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti return Result::failure(ArmErrorCode::CommandFailed, "failed to submit atomic cyclic position command"); } - if (k + 1 < samples.size()) { - const double next_t = samples[k + 1].time_s > 0.0 - ? samples[k + 1].time_s - : static_cast(k + 1) * fallback_dt; - std::this_thread::sleep_until(t0 + std::chrono::duration_cast( - std::chrono::duration(next_t))); - } } // Repeat the final position with zero velocity before checking feedback. @@ -609,7 +896,7 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti // evaluating feedback-based settling criteria. std::this_thread::sleep_for(std::chrono::milliseconds(1)); - const auto settle_result = waitForJointTarget_(target.position); + const auto settle_result = waitForJointTarget_(target.position, cancelled); if (!settle_result.ok()) { return settle_result; } @@ -620,38 +907,12 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity, const double acceleration, const double duration) { - (void)acceleration; - if (const auto stopped = safetyStopResult_("speedJ")) { - return *stopped; - } - std::string error; - if (!validateVelocityCommand_(velocity, error)) { - return Result::failure(ArmErrorCode::InvalidArgument, error); - } - - { - std::lock_guard lock(mutex_); - for (std::size_t i = 0; i < joint_names_.size(); ++i) { - auto motor = getMotor_(joint_names_[i]); - if (!motor) { - return Result::failure(ArmErrorCode::RobotNotReady, - "motor not found for joint: " + joint_names_[i]); - } - if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY) { - if (!motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY)) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to set cyclic velocity mode for joint: " + - joint_names_[i]); - } - } - if (!motor->commandCyclicVelocity(velocity.velocity[i] * speed_scaling_)) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to command cyclic velocity for joint: " + - joint_names_[i]); - } - } - } - + if (const auto stopped = safetyStopResult_("speedJ")) return *stopped; + JointVelocityCommand scaled = velocity; + const double scaling = speed_scaling_.load(); + for (auto& value : scaled.velocity) value *= scaling; + const auto result = sendJointVelocity_(scaled); + if (!result.ok()) return result; if (duration > 0.0) { std::this_thread::sleep_for(std::chrono::duration(duration)); return stopJ(acceleration); @@ -659,8 +920,44 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity, return Result::success(); } +Result MotorRobotArm::sendJointVelocity_(const JointVelocityCommand& velocity) +{ + if (const auto stopped = safetyStopResult_("velocity command")) { + if (std::all_of(velocity.velocity.begin(), velocity.velocity.end(), + [](double value) { return value == 0.0; })) { + return quickStopMotors_(); + } + return *stopped; + } + std::string error; + if (!validateVelocityCommand_(velocity, error)) + return Result::failure(ArmErrorCode::InvalidArgument, error); + + std::lock_guard lock(mutex_); + std::vector> motors; + motors.reserve(joint_names_.size()); + for (const auto& name : joint_names_) { + auto motor = getMotor_(name); + if (!motor) return Result::failure(ArmErrorCode::RobotNotReady, "motor not found: " + name); + motors.push_back(std::move(motor)); + } + for (const auto& motor : motors) { + if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY && + !motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY)) { + (void)quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandFailed, "failed to set cyclic velocity mode"); + } + } + if (!motor_manager_ || !motor_manager_->commandCyclicVelocitiesAtomic(motors, velocity.velocity)) { + (void)quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandFailed, "failed to submit cyclic velocity group"); + } + return Result::success(); +} + Result MotorRobotArm::stopJ(const double acceleration) { + joint_motion_stop_generation_.fetch_add(1); if (safetyStopRequested_()) { return Result::success(); } @@ -727,59 +1024,407 @@ Result MotorRobotArm::moveL(const CartesianPose& target, return Result::failure(ArmErrorCode::CommandFailed, "moveL execution failed"); } +Result MotorRobotArm::moveP(const CartesianPose& target, + const MotionOptions& options, + const FrameType frame) +{ + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + if (frame != FrameType::Base && frame != FrameType::Tool) { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "moveP supports Base and Tool frames only"); + } + for (const double value : {target.x, target.y, target.z, target.rx, target.ry, target.rz}) { + if (!std::isfinite(value)) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP target must be finite"); + } + } + return planAndExecuteJointPath_(options, [&](const std::vector& start, + std::vector& goal) { + Eigen::Matrix4d target_base = common::math::poseToMatrix(target); + if (frame == FrameType::Tool) { + Eigen::Matrix4d current_tcp; + if (!ik_solver_->fk(start, current_tcp, true)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP FK failed"); + } + target_base = (current_tcp * target_base).eval(); + } + ik_solver_->update_joints_state(start); + if (!ik_solver_->ik(target_base, goal, true)) { + return Result::failure(ArmErrorCode::OutOfWorkspace, "moveP target IK failed"); + } + return Result::success(); + }); +} + +Result MotorRobotArm::moveP(const JointPositionCommand& target, + const MotionOptions& options) +{ + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + std::string error; + if (!validatePositionCommand_(target, error)) { + return Result::failure(ArmErrorCode::InvalidArgument, error); + } + if (!std::all_of(target.position.begin(), target.position.end(), + [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP joint target must be finite"); + } + return planAndExecuteJointPath_(options, [&](const std::vector&, + std::vector& goal) { + goal = target.position; + return Result::success(); + }); +} + +Result MotorRobotArm::planAndExecuteJointPath_( + const MotionOptions& options, + const std::function&, std::vector&)>& resolve_goal) +{ + const auto stop_generation = joint_motion_stop_generation_.load(); + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + if (options.asynchronous || options.blend_radius != 0.0) { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "moveP supports synchronous motion without blending"); + } + const double scaling = speed_scaling_.load(); + if (!std::isfinite(options.velocity) || options.velocity <= 0.0 || + !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(options.jerk) || options.jerk <= 0.0 || + !std::isfinite(scaling) || scaling <= 0.0 || scaling > 1.0 || + (!options.joint_velocity_limits.empty() && options.joint_velocity_limits.size() != getDof())) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveP velocity, acceleration, jerk or speed scaling"); + } + for (const double limit : options.joint_velocity_limits) { + if (!std::isfinite(limit) || limit <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveP joint velocity limit"); + } + } + if (!ik_solver_ || !trajectory_smoother_ || !joint_path_planner_ || !path_collision_checker_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP requires motion.joint_path configuration"); + } + if (busy_.exchange(true)) { + return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); + } + struct MotionGuard { + std::atomic& busy; + std::function stop; + bool executing{false}; + bool completed{false}; + ~MotionGuard() { + if (executing && !completed) stop(); + busy.store(false); + } + } guard{busy_, [this] { quickStopMotors_(); }}; + + const auto cancelled = [&] { + return safetyStopRequested_() || joint_motion_stop_generation_.load() != stop_generation || + (options.cancellation_requested && options.cancellation_requested()); + }; + const auto interrupted = [&] { + if (const auto stopped = safetyStopResult_("moveP", true)) return *stopped; + return Result::failure(ArmErrorCode::CommandRejected, "moveP cancelled"); + }; + + try { + if (cancelled()) return interrupted(); + const auto cartesian_stop = stopCartesianMotionAndWait_(); + if (!cartesian_stop.ok()) return cartesian_stop; + + // 1. 从停止后的当前关节状态确定目标:关节目标直接使用,TCP 目标求 IK。 + JointPathRequest request; + std::vector velocity_now; + Eigen::VectorXd lower, upper, joint_velocity; + { + std::lock_guard lock(mutex_); + std::vector chain_joints; + if (!readArmState_(request.start, velocity_now) || + !ik_solver_->getChainJointNames(chain_joints) || chain_joints != joint_names_ || + !ik_solver_->getJointPositionLimits(lower, upper) || + !ik_solver_->getJointVelocityLimits(joint_velocity) || + lower.size() != dof_ || upper.size() != dof_ || joint_velocity.size() != dof_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP cannot read joint state/limits"); + } + if (!Eigen::Map(request.start.data(), dof_).allFinite()) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP joint feedback is not finite"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + if (request.start[j] < lower[j] - move_j_joint_limit_tolerance_rad_ || + request.start[j] > upper[j] + move_j_joint_limit_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP start exceeds joint limits: " + joint_names_[j]); + } + } + const auto resolved = resolve_goal(request.start, request.goal); + if (!resolved.ok()) return resolved; + if (request.goal.size() != getDof()) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP joint target size mismatch"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(request.goal[j]) || + request.goal[j] < lower[j] || request.goal[j] > upper[j]) { + return Result::failure(ArmErrorCode::InvalidArgument, + "moveP target exceeds joint limits: " + joint_names_[j]); + } + // Keep targets exact. Only normalize feedback overshoot within + // the configured tolerance so OMPL starts inside its bounds. + request.start[j] = std::clamp(request.start[j], lower[j], upper[j]); + } + } + + // 2. RRT、简化及样条复检共用本臂独立检测器和初始化时冻结的静态场景。 + request.lower_bounds.assign(lower.data(), lower.data() + lower.size()); + request.upper_bounds.assign(upper.data(), upper.data() + upper.size()); + request.is_cancelled = cancelled; + const auto& cfg = cfg_.motion().joint_path(); + CollisionValidationOptions collision_options; + collision_options.minimum_distance_m = cfg.has_minimum_distance_m() ? cfg.minimum_distance_m() : 0.01; + collision_options.joint_step_rad = cfg.rrt_connect().has_collision_check_step_rad() + ? cfg.rrt_connect().collision_check_step_rad() : 0.02; + collision_options.is_cancelled = cancelled; + const auto query_solver = std::dynamic_pointer_cast(ik_solver_); + collision_options.additional_state_valid = [&](const std::vector& q) { + if (!options.is_tcp_pose_valid) return true; + Eigen::Matrix4d tcp_pose_base; + bool fk_ok = false; + if (query_solver) { + // This query owns separate, mutex-protected Pinocchio work data; + // ordinary FK/IK queries may concurrently use the main work data. + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + fk_ok = query_solver->computePoseAndJacobianBaseAtQ( + q, true, tcp_pose_base, jacobian, rotation); + } else { + std::lock_guard lock(mutex_); + fk_ok = ik_solver_->fk(q, tcp_pose_base, true); + } + if (!fk_ok || !tcp_pose_base.allFinite()) { + throw std::runtime_error("moveP TCP constraint FK failed"); + } + return options.is_tcp_pose_valid(common::math::matrixToPose(tcp_pose_base)); + }; + request.is_state_valid = [&](const std::vector& q) { + return path_collision_checker_->isStateValid(q, collision_options); + }; + const auto path = joint_path_planner_->plan(request); + if (cancelled()) return interrupted(); + if (!path.ok()) { + return Result::failure(path.status == JointPathStatus::TimedOut ? ArmErrorCode::Timeout + : ArmErrorCode::CommandFailed, + "moveP path planning failed: " + path.message); + } + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] planning_time_ms=" + << path.planning_time_s * 1000.0; + if (path.waypoints.size() == 1) return Result::success(); + + // 3. 独立五次 B 样条构造时间轨迹;按解析导数上界统一缩放时间。 + const double period_s = joint_trajectory_sample_period_s_; + if (!std::isfinite(period_s) || period_s <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint trajectory sample period"); + } + const double check_step = collision_options.joint_step_rad; + MotionOptions validation_limits = options; + validation_limits.velocity *= scaling; + validation_limits.joint_velocity_limits.resize(getDof()); + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(joint_velocity[j]) || joint_velocity[j] <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint velocity limit"); + } + double velocity = std::min(options.velocity, joint_velocity[j]); + if (!options.joint_velocity_limits.empty()) { + velocity = std::min(velocity, options.joint_velocity_limits[j]); + } + validation_limits.joint_velocity_limits[j] = + std::min(velocity * scaling, check_step / period_s); + } + const auto trajectory_start = std::chrono::steady_clock::now(); + validation_limits.cancellation_requested = cancelled; + JointTrajectory samples; + if (!trajectory_smoother_->smooth(path.waypoints, validation_limits, period_s, samples)) { + if (cancelled()) return interrupted(); + return Result::failure(ArmErrorCode::CommandFailed, "moveP B-spline planning failed"); + } + const double duration = samples.back().time_s; + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] trajectory_planning_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - trajectory_start).count() + << ", trajectory_time_s=" << duration << ", path=quintic_bspline"; + + // 运动限值检查后,由碰撞检测器负责整条轨迹的离散复检。 + const auto validation_start = std::chrono::steady_clock::now(); + if (!validateJointTrajectory(samples, getDof(), validation_limits)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP smoothed trajectory violates motion limits"); + } + for (std::size_t i = 0; i < samples.size(); ++i) { + if (cancelled()) return interrupted(); + const auto& to = samples[i].position; + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(samples[i].acceleration[j]) || !std::isfinite(samples[i].jerk[j]) || + std::abs(samples[i].acceleration[j]) > options.acceleration + 1e-6 || + std::abs(samples[i].jerk[j]) > options.jerk + 1e-6) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP B-spline violates acceleration/jerk limits: " + joint_names_[j]); + } + if (to[j] < lower[j] - move_j_joint_limit_tolerance_rad_ || + to[j] > upper[j] + move_j_joint_limit_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP smoothed trajectory exceeds joint limits: " + joint_names_[j]); + } + } + } + const auto collision_check = path_collision_checker_->checkTrajectory(samples, collision_options); + if (cancelled()) return interrupted(); + if (!collision_check.valid) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP smoothed trajectory failed collision/clearance check: " + collision_check.error); + } + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] validation_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - validation_start).count() + << ", validity_checks=" << collision_check.validity_checks; + if (options.trajectory_callback) options.trajectory_callback(samples); + + std::vector> motors; + for (const auto& name : joint_names_) { + auto motor = getMotor_(name); + if (!motor) return Result::failure(ArmErrorCode::RobotNotReady, "motor not found: " + name); + motors.push_back(std::move(motor)); + } + if (cancelled()) return interrupted(); + const auto current = readJointPosition_(); + if (current.size() != request.start.size()) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP joint feedback is unavailable"); + } + for (std::size_t j = 0; j < current.size(); ++j) { + if (!std::isfinite(current[j]) || + std::abs(current[j] - request.start[j]) > move_j_position_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandRejected, "arm moved during moveP planning"); + } + } + guard.executing = true; + { + std::lock_guard lock(mutex_); + if (cancelled()) return interrupted(); + for (const auto& motor : motors) { + if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_POSITION && + !motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP failed to set cyclic position mode"); + } + } + } + // 4. 按轨迹的绝对时间发送位置和速度前馈,避免逐周期累计计时误差。 + const auto motion_start = std::chrono::steady_clock::now(); + std::vector position(getDof()), velocity(getDof()); + for (std::size_t k = 1; k < samples.size(); ++k) { + const auto& sample = samples[k]; + const auto deadline = motion_start + + std::chrono::duration_cast( + std::chrono::duration(sample.time_s)); + do { + if (cancelled()) return interrupted(); + std::this_thread::sleep_until(std::min(deadline, + std::chrono::steady_clock::now() + std::chrono::milliseconds(1))); + } while (std::chrono::steady_clock::now() < deadline); + position = sample.position; + velocity = sample.velocity; + if (k + 1 == samples.size()) { + position = request.goal; + std::fill(velocity.begin(), velocity.end(), 0.0); + } + std::lock_guard lock(mutex_); + if (cancelled()) return interrupted(); + if (!motor_manager_->commandCyclicPositionsAtomic(motors, position, velocity)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP cyclic position command failed"); + } + } + const auto settled = waitForJointTarget_(request.goal, cancelled, "moveP"); + if (!settled.ok()) return settled; + guard.completed = true; + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] waypoints=" << path.waypoints.size() + << ", control_cycles=" << samples.size() - 1; + return Result::success(); + } catch (const std::exception& error) { + if (cancelled()) return interrupted(); + return Result::failure(ArmErrorCode::CommandFailed, std::string("moveP failed: ") + error.what()); + } +} + Result MotorRobotArm::speedL(const CartesianVelocity& velocity, const double acceleration, const double duration, const FrameType frame) { - if (const auto stopped = safetyStopResult_("speedL")) { - return *stopped; - } - if (busy_.load()) { - return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); - } - if (!cartesian_velocity_controller_) { - return Result::failure(ArmErrorCode::RobotNotReady, "cartesian velocity controller is not initialized"); - } - return cartesian_velocity_controller_->speedL(velocity, acceleration, duration, frame); + SpeedLOptions options; + options.acceleration = acceleration; + return speedL(velocity, options, duration, frame); } Result MotorRobotArm::stopL(const std::optional acceleration) { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return Result::success(); } - return cartesian_velocity_controller_->stop(acceleration); + return speed_l_executor_->stop(acceleration); } Result MotorRobotArm::speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, const double duration, const FrameType frame) { if (const auto stopped = safetyStopResult_("speedL")) return *stopped; - if (busy_.load() || !cartesian_velocity_controller_) { + if (busy_.load() || !speed_l_executor_) { return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy or velocity controller is unavailable"); } - return cartesian_velocity_controller_->speedL(velocity, options, duration, frame); + return speed_l_executor_->speedL(velocity, options, duration, frame); } SpeedLReference MotorRobotArm::getSpeedLReference() const { - return cartesian_velocity_controller_ ? cartesian_velocity_controller_->getReference() : SpeedLReference{}; + return speed_l_executor_ ? speed_l_executor_->getReference() : SpeedLReference{}; +} + +Result MotorRobotArm::getSpeedLResult() const +{ + return speed_l_executor_ ? speed_l_executor_->lastResult() : + Result::failure(ArmErrorCode::RobotNotReady, "velocity executor is unavailable"); +} + +bool MotorRobotArm::isFault() const +{ + return speed_l_executor_ && speed_l_executor_->faulted(); +} + +Result MotorRobotArm::clearFault() +{ + return speed_l_executor_ ? speed_l_executor_->clearFault() : Result::success(); +} + +Result MotorRobotArm::recoverSpeedLPlanningFault() +{ + if (const auto stopped = safetyStopResult_("recover speedL planning fault")) return *stopped; + if (!isConnected()) { + return Result::failure(ArmErrorCode::NotConnected, "arm is not connected"); + } + if (busy_.load()) { + return Result::failure(ArmErrorCode::RobotNotReady, "joint motion is still active"); + } + const auto result = speed_l_executor_ ? speed_l_executor_->clearPlanningFault() : Result::success(); + if (const auto stopped = safetyStopResult_("recover speedL planning fault")) return *stopped; + return result; } Result MotorRobotArm::stopMotion() { + joint_motion_stop_generation_.fetch_add(1); const auto cartesian_stop = stopCartesianMotionAndWait_(); - if (!cartesian_stop.ok()) { - return cartesian_stop; - } - return stopJ(0.0); + const auto result = cartesian_stop.ok() ? stopJ(0.0) : cartesian_stop; + if (speed_l_executor_) speed_l_executor_->recordStopFailure(result); + return result; } Result MotorRobotArm::shutdown() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); + joint_motion_stop_generation_.fetch_add(1); + if (speed_l_executor_) { + const auto result = speed_l_executor_->shutdown(); + if (!result.ok()) return result; } return stopJ(0.0); } @@ -954,16 +1599,16 @@ CartesianPose MotorRobotArm::fk(const bool is_tcp) CartesianVelocity MotorRobotArm::getSpeedLCommandTwistBase() const { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return {}; } - return cartesian_velocity_controller_->getCommandTwistBase(); + return speed_l_executor_->getCommandTwistBase(); } bool MotorRobotArm::busy() const { return busy_.load() || - (cartesian_velocity_controller_ && cartesian_velocity_controller_->busy()); + (speed_l_executor_ && speed_l_executor_->busy()); } bool MotorRobotArm::containsJoint_(const std::string& joint_name) const @@ -1022,28 +1667,30 @@ std::vector MotorRobotArm::readJointPosition_() const Result MotorRobotArm::stopCartesianMotionAndWait_() { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return Result::success(); } - if (cartesian_velocity_controller_->busy()) { - const auto stop_result = cartesian_velocity_controller_->stop(); + if (speed_l_executor_->busy()) { + const auto stop_result = speed_l_executor_->stop(); if (!stop_result.ok()) { - return stop_result; + // A fault may finish the command between busy() and stop(). Join + // and verify the final zero command instead of returning its old error. + return speed_l_executor_->shutdown(); } const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration( - cartesian_velocity_controller_->stopTimeoutS()); - while (cartesian_velocity_controller_->busy() && + speed_l_executor_->stopTimeoutS()); + while (speed_l_executor_->busy() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (cartesian_velocity_controller_->busy()) { + if (speed_l_executor_->busy()) { // Do not start a position trajectory while the worker can still // issue velocity commands. Shutdown joins it and sends one final // zero-velocity command before reporting the timeout. - cartesian_velocity_controller_->shutdown(); + speed_l_executor_->shutdown(); return Result::failure( ArmErrorCode::Timeout, "timed out waiting for Cartesian velocity motion to stop"); @@ -1052,15 +1699,19 @@ Result MotorRobotArm::stopCartesianMotionAndWait_() // The worker may be idle but still joinable. Joining it here removes any // last command/worker race before the next motion mode is selected. - cartesian_velocity_controller_->shutdown(); - return Result::success(); + // This operation reports whether motion has stopped. A previous planning + // failure remains available through getSpeedLResult()/isFault(), but must + // not reject a position-mode recovery after a successful stop. + return speed_l_executor_->shutdown(); } -Result MotorRobotArm::waitForJointTarget_(const std::vector& target) const +Result MotorRobotArm::waitForJointTarget_(const std::vector& target, + const std::function& is_cancelled, + const std::string& command) const { if (target.size() != joint_names_.size()) { return Result::failure(ArmErrorCode::InvalidArgument, - "moveJ target size mismatch while settling"); + command + " target size mismatch while settling"); } struct JointFeedback { @@ -1074,9 +1725,12 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con int stable_samples = 0; int max_stable_samples = 0; while (std::chrono::steady_clock::now() < deadline) { - if (const auto stopped = safetyStopResult_("moveJ", true)) { + if (const auto stopped = safetyStopResult_(command, true)) { return *stopped; } + if (is_cancelled && is_cancelled()) { + return Result::failure(ArmErrorCode::CommandRejected, command + " cancelled"); + } bool settled = true; for (std::size_t i = 0; i < joint_names_.size(); ++i) { @@ -1084,7 +1738,7 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con if (!motor) { return Result::failure( ArmErrorCode::RobotNotReady, - "motor not found while waiting for moveJ target: " + joint_names_[i]); + "motor not found while waiting for " + command + " target: " + joint_names_[i]); } const double position = motor->getQ(); const double velocity = motor->getQd(); @@ -1105,7 +1759,7 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - CMVR_LOG(ERROR) << "[MotorRobotArm] moveJ target did not settle before timeout: " << id_ + CMVR_LOG(ERROR) << "[MotorRobotArm] " << command << " target did not settle before timeout: " << id_ << ", timeout_s=" << move_j_settle_timeout_s_ << ", sample_count=" << sample_count << ", stable_samples=" << stable_samples @@ -1137,18 +1791,56 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con << ", velocity_ok=" << (velocity_ok ? "true" : "false"); } return Result::failure(ArmErrorCode::Timeout, - "timed out waiting for moveJ target to settle"); + "timed out waiting for " + command + " target to settle"); +} + +bool MotorRobotArm::configureJointPathPlanner_() +{ + joint_path_planner_.reset(); + path_collision_checker_.reset(); + if (!cfg_.motion().has_joint_path()) return true; + + const auto& cfg = cfg_.motion().joint_path(); + joint_path_planner_ = JointPathPlannerFactory::create(cfg); + const double clearance = cfg.has_minimum_distance_m() ? cfg.minimum_distance_m() : 0.01; + if (!joint_path_planner_ || !std::isfinite(clearance) || clearance < 0.0 || + motor_cfg_.upd_freq() <= 0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid joint_path configuration: " << id_; + return false; + } + auto checker = std::make_unique(); + std::string error; + if (!model_.loadCollisionGeometry( + ConfigHelper::resolveResourceFile(cfg.collision_checker().urdf_path()))) { + return false; + } + if (!checker->init(cfg.collision_checker(), model_, &error)) { + CMVR_LOG(ERROR) << "[MotorRobotArm] joint_path collision checker: " << error; + return false; + } + path_collision_checker_ = std::move(checker); + return true; } bool MotorRobotArm::configureAlgorithms_() { - // Optional settling fields are read once during initialization so every + // Optional limit/settling fields are read once during initialization so every // MoveJ command uses one consistent set of safety criteria. + move_j_joint_limit_tolerance_rad_ = 1e-5; move_j_settle_timeout_s_ = 2.0; move_j_position_tolerance_rad_ = 2e-3; move_j_velocity_tolerance_rad_s_ = 2e-2; move_j_stable_sample_count_ = 3; const auto& move_j_config = cfg_.motion().move_j(); + if (move_j_config.has_joint_limit_tolerance_rad()) { + const double value = move_j_config.joint_limit_tolerance_rad(); + if (!std::isfinite(value) || value < 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid moveJ joint_limit_tolerance_rad: " + << value; + return false; + } + move_j_joint_limit_tolerance_rad_ = value; + } if (move_j_config.has_settle_timeout_s()) { const double value = move_j_config.settle_timeout_s(); if (!std::isfinite(value) || value <= 0.0) { @@ -1195,49 +1887,98 @@ bool MotorRobotArm::configureAlgorithms_() return false; } - joint_planner_ = JointMotionPlannerFactory::create(cfg_.motion().move_j()); - if (!joint_planner_) { + auto smoother_config = cfg_.motion().joint_trajectory_smoother(); + if (!cfg_.motion().has_joint_trajectory_smoother()) { + smoother_config.mutable_quintic_bspline(); + } + joint_trajectory_sample_period_s_ = smoother_config.has_sample_period_s() + ? smoother_config.sample_period_s() : 0.001; + if (!std::isfinite(joint_trajectory_sample_period_s_) || joint_trajectory_sample_period_s_ <= 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid joint trajectory sample period"; + return false; + } + trajectory_smoother_ = JointTrajectorySmootherFactory::create(smoother_config); + if (!trajectory_smoother_) { return false; } - ik_solver_ = cmvr::IKSolverFactory::create(cfg_.kinematics()); - if (!ik_solver_ || !ik_solver_->init()) { + if (cfg_.has_kinematics()) { + ik_solver_ = cmvr::IKSolverFactory::create(cfg_.kinematics()); + if (!ik_solver_ || !ik_solver_->init()) { + return false; + } + model_ = ik_solver_->getRobotModel(); + model_.name = id_; + model_.manufacturer = "cmvr"; + if (!model_.valid() || !model_.hasKinematics() || model_.joint_names != joint_names_) { + CMVR_LOG(ERROR) << "[MotorRobotArm] robot model does not match configured joints: " << id_; + return false; + } + } else { + if (cfg_.motion().has_move_l() || cfg_.motion().has_speed_l() || + cfg_.motion().has_joint_path()) { + CMVR_LOG(ERROR) << "[MotorRobotArm] move_l, speed_l and joint_path require " + "kinematics configuration: " << id_; + return false; + } + model_.joint_limits.clear(); + for (const auto& joint_name : joint_names_) { + const auto motor = getMotor_(joint_name); + if (!motor) return false; + const auto info = motor->motorInfo(); + if (!std::isfinite(info.limit_q_lb) || !std::isfinite(info.limit_q_ub) || + info.limit_q_lb >= info.limit_q_ub || !std::isfinite(info.limit_qd) || + info.limit_qd <= 0.0 || !std::isfinite(info.limit_qdd) || info.limit_qdd < 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid configured motor limits: " << joint_name; + return false; + } + model_.joint_limits.push_back(JointLimit{ + info.limit_q_lb, info.limit_q_ub, info.limit_qd, info.limit_qdd}); + } + } + + if (!configureJointPathPlanner_()) { return false; } + if (!cfg_.motion().has_move_l() && !cfg_.motion().has_speed_l()) { + return true; + } auto pinocchio_solver = std::dynamic_pointer_cast(ik_solver_); if (!pinocchio_solver) { return false; } - const auto& move_l = cfg_.motion().move_l(); + if (cfg_.motion().has_move_l()) { + cartesian_planner_ = CartesianMotionPlannerFactory::createMoveL( + cfg_.motion().move_l(), pinocchio_solver); + if (!cartesian_planner_) return false; + } + if (!cfg_.motion().has_speed_l()) return true; const auto& speed_l = cfg_.motion().speed_l(); - auto cartesian_motion = CartesianMotionPlannerFactory::create(move_l, speed_l, pinocchio_solver); - if (!cartesian_motion) { - return false; + auto cartesian_velocity = CartesianMotionPlannerFactory::createSpeedL( + speed_l, pinocchio_solver, getDof()); + if (!cartesian_velocity) return false; + SpeedLExecutor::BeginCycleCallback begin_cycle; + SpeedLExecutor::EndCycleCallback end_cycle; + if (auto world = MotorManager::mujocoWorldFor(motor_system_id_)) { + const auto controller_id = id_; + begin_cycle = [world, controller_id] { return world->beginControlCycle(controller_id); }; + end_cycle = [world, controller_id](bool finished) { world->endControlCycle(controller_id, finished); }; } - const auto* speed_l_config = CartesianMotionPlannerFactory::speedLConfig(speed_l); - const auto* move_l_config = CartesianMotionPlannerFactory::moveLConfig(move_l); - if (!speed_l_config || !move_l_config) { - return false; - } - if (!cartesian_motion->configureMoveL(*move_l_config) || - !cartesian_motion->configureSpeedL(*speed_l_config, getDof())) { - return false; - } - - cartesian_planner_ = cartesian_motion; - cartesian_velocity_controller_ = std::make_unique( - toCartesianVelocityControllerConfig_( + speed_l_executor_ = std::make_unique( + toSpeedLExecutorConfig_( speed_l.speed_l_controller().cartesian_velocity_controller()), - cartesian_planner_, + std::move(cartesian_velocity), getDof(), [this](std::vector& q, std::vector& qd) { return readArmState_(q, qd); }, - [this](const JointVelocityCommand& velocity, const double acceleration) { - return speedJ(velocity, acceleration, 0.0); - }); + [this](const JointVelocityCommand& velocity) { + return sendJointVelocity_(velocity); + }, + [this] { return speed_scaling_.load(); }, + std::move(begin_cycle), std::move(end_cycle)); return true; } @@ -1292,25 +2033,17 @@ bool MotorRobotArm::executeMoveLTrajectory_(const CartesianJointTrajectory& traj return true; } -CartesianVelocityController::Config MotorRobotArm::toCartesianVelocityControllerConfig_( +SpeedLExecutor::Config MotorRobotArm::toSpeedLExecutorConfig_( const config::CartesianVelocityControllerConfig& config) { - CartesianVelocityController::Config result; - result.control_period_s = config.control_period_s() > 0.0 ? config.control_period_s() : result.control_period_s; - result.stop_twist_norm = config.stop_twist_norm() > 0.0 ? config.stop_twist_norm() : result.stop_twist_norm; - result.stop_command_velocity_norm = - config.stop_command_velocity_norm() > 0.0 ? config.stop_command_velocity_norm() - : result.stop_command_velocity_norm; - result.stop_measured_velocity_norm = - config.stop_measured_velocity_norm() > 0.0 ? config.stop_measured_velocity_norm() - : result.stop_measured_velocity_norm; - result.stop_acceleration = - config.stop_acceleration() > 0.0 ? config.stop_acceleration() - : result.stop_acceleration; - if (config.has_stop_timeout_s() && std::isfinite(config.stop_timeout_s()) && - config.stop_timeout_s() > 0.0) { - result.stop_timeout_s = config.stop_timeout_s(); - } + SpeedLExecutor::Config result; + // Defaults and normalization belong to SpeedLExecutor. + result.control_period_s = config.control_period_s(); + result.stop_twist_norm = config.stop_twist_norm(); + result.stop_command_velocity_norm = config.stop_command_velocity_norm(); + result.stop_measured_velocity_norm = config.stop_measured_velocity_norm(); + result.stop_acceleration = config.stop_acceleration(); + result.stop_timeout_s = config.stop_timeout_s(); return result; } diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp index 82e473f9..e4102dda 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp @@ -4,18 +4,27 @@ #include #include #include +#include #include +#include #include #include #include +#include +#include #include #include #include #include #include +#include +#include "cmvr/config/touch_screen_task_config/touch_screen_task_config.pb.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" +#include "common/math/proto_geometry.h" +#include "common/math/transform_math.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_viewer/include/mujoco_viewer.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -85,11 +94,8 @@ void waitFor(Predicate predicate, const std::chrono::milliseconds timeout) struct ScenarioOutcome { Result move_j_initial{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result move_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; - Result speed_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; double move_j_initial_error{std::numeric_limits::infinity()}; double move_l_error{std::numeric_limits::infinity()}; - double speed_l_command_x{0.0}; - double speed_l_delta_x{0.0}; std::string worker_error; }; @@ -128,6 +134,8 @@ protected: { project_root_ = findProjectRoot(); ASSERT_FALSE(project_root_.empty()); + ConfigHelper::setConfigRootFromFile( + (project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string()); config::MujocoWorldRootConfig world_root_config; ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( @@ -159,12 +167,12 @@ protected: &root_config)); ASSERT_GT(root_config.arm().robot_arms_size(), 0); - config::RobotArmConfig arm_config = root_config.arm().robot_arms(0); + arm_config_ = root_config.arm().robot_arms(0); setKinematicsUrdfPath( - arm_config, + arm_config_, (project_root_ / "model/xiaoyan_description/dual_arm.urdf").string()); - arm_ = std::make_unique(arm_config); + arm_ = std::make_unique(arm_config_); ASSERT_NO_THROW(arm_->init()); } @@ -186,14 +194,35 @@ protected: std::shared_ptr motor_system_; std::shared_ptr world_; std::unique_ptr arm_; + config::RobotArmConfig arm_config_; + void runSpeedL(bool angular); + void runTouchLog(bool adaptive, double min_speed_ratio = 0); + void configureAdaptiveSpeed(bool enable, double min_speed_ratio = 0) { + // Let startup position actuators settle before replacing the arm. Its + // shutdown switches motors to zero velocity and would freeze startup sag. + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + ASSERT_TRUE(arm_->shutdown().ok()); + arm_.reset(); + auto* policy = arm_config_.mutable_motion()->mutable_speed_l() + ->mutable_pinocchio_cartesian_motion_planner()->mutable_adaptive_speed(); + policy->set_enable(enable); + policy->set_lookahead_s(.15); + policy->set_min_speed_ratio(min_speed_ratio); + arm_ = std::make_unique(arm_config_); + ASSERT_TRUE(arm_->init()); + } }; TEST_P(MotorRobotArmMujocoTest, MoveJ) { MotorRobotArm& arm = *arm_; - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } ScenarioOutcome outcome; std::thread scenario([&] { @@ -220,12 +249,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ) outcome.worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); std::cout << "[MotorRobotArmMujocoTest] moveJ initial max error: " @@ -236,12 +269,53 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ) EXPECT_LT(outcome.move_j_initial_error, 0.10); } +TEST_P(MotorRobotArmMujocoTest, MoveJWithoutKinematics) +{ + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + arm_.reset(); + arm_config_.clear_kinematics(); + arm_config_.clear_motion(); + arm_config_.mutable_motion()->mutable_move_j()->set_settle_timeout_s(2.0); + arm_ = std::make_unique(arm_config_); + if (!arm_->init() || arm_->kinematicsSolver() || + arm_->getRobotState().fault) { + throw std::runtime_error("Joint-only arm initialization failed"); + } + + auto target = arm_->getJointState().position; + for (auto& q : target) q += 0.02; + MotionOptions options; + options.velocity = 0.2; + options.acceleration = 0.5; + options.jerk = 5.0; + const auto result = arm_->moveJ(JointPositionCommand{target}, options); + if (!result.ok()) throw std::runtime_error(result.message); + std::cout << "Joint-only MoveJ max position error: " + << maxPositionError(arm_->getJointState().position, target) << std::endl; + + target[0] = arm_->getRobotModel().joint_limits[0].upper + 0.1; + if (arm_->moveJ(JointPositionCommand{target}, options).ok()) { + throw std::runtime_error("MoveJ accepted a target outside the motor limits"); + } + if (arm_->moveL(CartesianPose{}, options).ok() || + arm_->speedL(CartesianVelocity{}, 0.5, 0.1).ok()) { + throw std::runtime_error("Unconfigured Cartesian motion was accepted"); + } +} + TEST_P(MotorRobotArmMujocoTest, MoveL) { MotorRobotArm& arm = *arm_; + const bool uses_qp = std::string(GetParam().name) == "QpIk"; + Result rejected_fast_move_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; + double rejected_motion_m = std::numeric_limits::quiet_NaN(); - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } ScenarioOutcome outcome; std::thread scenario([&] { @@ -276,6 +350,14 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) cartesian_options.acceleration = 20; cartesian_options.jerk = 100.0; + if (uses_qp) { + // At 0.8 m/s, this path requires elbow velocity below -5 rad/s. + // Hard Cartesian equality must reject it before execution. + rejected_fast_move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base); + rejected_motion_m = translationError(arm.getTcpPose(), move_l_start); + cartesian_options.velocity = 0.2; + } + std::cout << "[MotorRobotArmMujocoTest] moveL target pose" << std::endl; outcome.move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base); waitFor([&] { @@ -286,12 +368,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) outcome.worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::milliseconds(10000)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::milliseconds(10000)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); std::cout << "[MotorRobotArmMujocoTest] moveJ setup max error: " @@ -301,75 +387,684 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) EXPECT_TRUE(outcome.worker_error.empty()) << outcome.worker_error; EXPECT_TRUE(outcome.move_j_initial.ok()) << outcome.move_j_initial.message; EXPECT_LT(outcome.move_j_initial_error, 0.10); + if (uses_qp) { + std::cout << "[MotorRobotArmMujocoTest] rejected fast moveL: " + << rejected_fast_move_l.message << ", displacement_m=" << rejected_motion_m << std::endl; + EXPECT_EQ(rejected_fast_move_l.code, ArmErrorCode::CommandFailed); + EXPECT_LT(rejected_motion_m, 1e-6); + EXPECT_LT(outcome.move_l_error, 0.0002); + } EXPECT_TRUE(outcome.move_l.ok()) << outcome.move_l.message; EXPECT_LT(outcome.move_l_error, 0.04); } -TEST_P(MotorRobotArmMujocoTest, SpeedL) +void MotorRobotArmMujocoTest::runSpeedL(const bool angular) { MotorRobotArm& arm = *arm_; + const double speed = angular ? .1 : .05; + const auto leg_duration = std::chrono::milliseconds(angular ? 3000 : 800); + const char* label = angular ? "SpeedLRotation" : "SpeedL6D"; - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); - ScenarioOutcome outcome; + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } + struct LegResult { + int axis; + bool reversal; + bool completed; + double sign; + double displacement; + double lateral_displacement; + double command_velocity; + double actual_velocity; + double reverse_ms; + }; + std::vector legs; + std::array stopped{}; + std::string worker_error; std::thread scenario([&] { try { - if (!world_ || !world_->isRunning()) { - throw std::runtime_error("MuJoCo world is not running"); - } - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - - const std::vector move_j_initial{ - 0.25, 1.00, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0 + const auto require = [](const Result& result) { + if (!result.ok()) throw std::runtime_error(result.message); }; - MotionOptions joint_options; - joint_options.velocity = 2.8; - joint_options.acceleration = 20.0; + const int site = mj_name2id(world_->model(), mjOBJ_SITE, "R_FINGER_TIP_SITE"); + if (site < 0) throw std::runtime_error("TCP site not found"); + std::vector jacobian(3 * world_->model()->nv); + struct Sample { + Eigen::Vector3d position; + Eigen::Matrix3d rotation; + Eigen::Vector3d velocity{Eigen::Vector3d::Zero()}; + }; + const auto sample = [&] { + std::lock_guard lock(world_->mutex()); + const auto* model = world_->model(); + const auto* data = world_->data(); + mj_jacSite(model, data, angular ? nullptr : jacobian.data(), + angular ? jacobian.data() : nullptr, site); + Sample value; + for (int axis = 0; axis < 3; ++axis) { + value.position[axis] = data->site_xpos[3 * site + axis]; + for (int j = 0; j < 3; ++j) + value.rotation(axis, j) = data->site_xmat[9 * site + 3 * axis + j]; + for (int j = 0; j < model->nv; ++j) + value.velocity[axis] += jacobian[axis * model->nv + j] * data->qvel[j]; + } + // This model's fixed PELVIS_S has world-aligned Base axes. + return value; + }; + const std::vector initial{ + .25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0 + }; + MotionOptions move; + move.velocity = 2.8; + move.acceleration = 20.0; + SpeedLOptions options; + options.acceleration = .5; + if (!angular) options.linear_jerk = 10; + options.continuous_linear_reversal = true; - std::cout << "[MotorRobotArmMujocoTest] moveJ setup pose" << std::endl; - outcome.move_j_initial = arm.moveJ(JointPositionCommand{move_j_initial}, joint_options); - waitFor([&] { - return maxPositionError(arm.getJointState().position, move_j_initial) < 0.04; - }, std::chrono::seconds(2)); - outcome.move_j_initial_error = maxPositionError(arm.getJointState().position, move_j_initial); + // Allow the newly started position actuators to settle at zero. + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + for (int axis = 0; axis < 3; ++axis) { + // Reset between axes; opposite commands below have no stopL in between. + require(arm.moveJ(JointPositionCommand{initial}, move)); + waitFor([&] { return maxPositionError(arm.getJointState().position, initial) < .04; }, + std::chrono::seconds(2)); + if (maxPositionError(arm.getJointState().position, initial) >= .04) + throw std::runtime_error("speedL setup pose did not settle"); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); - std::this_thread::sleep_for(std::chrono::seconds(2)); - - const CartesianPose speed_l_start = arm.getTcpPose(); - CartesianVelocity cartesian_velocity; - cartesian_velocity.vx = 0.05; - - std::cout << "[MotorRobotArmMujocoTest] speedL" << std::endl; - outcome.speed_l = arm.speedL(cartesian_velocity, 0.5, 0.0, FrameType::Base); - std::this_thread::sleep_for(std::chrono::seconds(1)); - outcome.speed_l_command_x = arm.getSpeedLCommandTwistBase().vx; - outcome.speed_l_delta_x = arm.getTcpPose().x - speed_l_start.x; - (void)arm.stopL(0.5); - waitFor([&] { return !arm.busy(); }, std::chrono::seconds(3)); + for (int leg = 0; leg < 3; ++leg) { + const double sign = leg == 1 ? -1.0 : 1.0; + const auto start = sample(); + if (leg > 0 && sign * start.velocity[axis] > -.4 * speed) + throw std::runtime_error("reversal did not start while moving in opposite direction"); + CartesianVelocity target; + const std::array components = angular + ? std::array{&CartesianVelocity::wx, &CartesianVelocity::wy, &CartesianVelocity::wz} + : std::array{&CartesianVelocity::vx, &CartesianVelocity::vy, &CartesianVelocity::vz}; + target.*components[axis] = sign * speed; + std::cout << '[' << label << "] " << GetParam().name << " target=" + << (sign > 0 ? '+' : '-') << "XYZ"[axis] + << " reverse=" << (leg > 0) << std::endl; + const auto begin = std::chrono::steady_clock::now(); + require(arm.speedL(target, options, 0.0, FrameType::Base)); + double reverse_ms = -1; + int direction_samples = 0; + bool completed = true; + auto reached = start; + auto next = begin; + while (std::chrono::steady_clock::now() - begin < leg_duration) { + reached = sample(); + if (!arm.busy()) { + completed = false; + break; + } + direction_samples = sign * reached.velocity[axis] > .1 * speed ? direction_samples + 1 : 0; + if (leg > 0 && direction_samples >= 5 && reverse_ms < 0) + reverse_ms = std::chrono::duration( + std::chrono::steady_clock::now() - begin).count(); + next += std::chrono::milliseconds(5); + std::this_thread::sleep_until(next); + } + const auto command = arm.getSpeedLCommandTwistBase(); + Eigen::Vector3d displacement = reached.position - start.position; + if (angular) { + const Eigen::AngleAxisd delta(reached.rotation * start.rotation.transpose()); + displacement = delta.axis() * delta.angle(); + } + Eigen::Vector3d lateral = displacement; + lateral[axis] = 0; + legs.push_back({axis, leg > 0, completed, sign, + sign * displacement[axis], lateral.norm(), + sign * (command.*components[axis]), sign * reached.velocity[axis], reverse_ms}); + const auto& result = legs.back(); + std::cout << '[' << label << "] " << GetParam().name << " result=" + << (sign > 0 ? '+' : '-') << "XYZ"[axis] + << (angular ? " angle_deg=" : " displacement_mm=") + << result.displacement * (angular ? 180 / M_PI : 1000) + << (angular ? " cross_axis_deg=" : " lateral_mm=") + << result.lateral_displacement * (angular ? 180 / M_PI : 1000) + << (angular ? " command_rad_s=" : " command_m_s=") << result.command_velocity + << (angular ? " actual_rad_s=" : " actual_m_s=") << result.actual_velocity + << " reverse_ms=" << result.reverse_ms + << " completed=" << completed << std::endl; + // Keep a failed leg in the results, then stop and test the next axis. + if (!completed) break; + } + require(arm.stopL(.5)); + waitFor([&] { return !arm.busy(); }, std::chrono::seconds(3)); + const double residual_speed = sample().velocity.norm(); + stopped[axis] = !arm.busy() && residual_speed < .01; + std::cout << '[' << label << "] " << GetParam().name << " stop=" << "XYZ"[axis] + << " ok=" << stopped[axis] + << (angular ? " residual_rad_s=" : " residual_m_s=") << residual_speed << std::endl; + if (!stopped[axis]) throw std::runtime_error("speedL did not stop cleanly"); + } } catch (const std::exception& error) { - outcome.worker_error = error.what(); + worker_error = error.what(); + (void)arm.stopL(.5); + } + if (viewer) { + std::this_thread::sleep_for(std::chrono::seconds(3)); + viewer->requestStop(); } - - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - viewer.requestStop(); }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); - std::cout << "[MotorRobotArmMujocoTest] moveJ setup max error: " - << outcome.move_j_initial_error - << ", speedL command x: " << outcome.speed_l_command_x - << ", speedL x delta: " << outcome.speed_l_delta_x << std::endl; + EXPECT_TRUE(worker_error.empty()) << worker_error; + EXPECT_EQ(legs.size(), 9U); // Six directions and both reversal orders on each axis. + for (std::size_t i = 0; i < legs.size(); ++i) { + const auto& leg = legs[i]; + SCOPED_TRACE(::testing::Message() << "axis=" << "XYZ"[leg.axis] << " sign=" << leg.sign); + EXPECT_TRUE(leg.completed); + EXPECT_GT(leg.displacement, .005); + EXPECT_NEAR(leg.command_velocity, speed, .1 * speed); + EXPECT_NEAR(leg.actual_velocity, speed, .3 * speed); + if (leg.reversal) { + EXPECT_GT(leg.reverse_ms, 0); + EXPECT_LT(leg.reverse_ms, 600); + } + } + for (bool axis_stopped : stopped) EXPECT_TRUE(axis_stopped); +} - EXPECT_TRUE(outcome.worker_error.empty()) << outcome.worker_error; - EXPECT_TRUE(outcome.move_j_initial.ok()) << outcome.move_j_initial.message; - EXPECT_LT(outcome.move_j_initial_error, 0.10); - EXPECT_TRUE(outcome.speed_l.ok()) << outcome.speed_l.message; - EXPECT_GT(outcome.speed_l_command_x, 0.01); - EXPECT_GT(outcome.speed_l_delta_x, 0.003); +TEST_P(MotorRobotArmMujocoTest, SpeedL) { runSpeedL(false); } +TEST_P(MotorRobotArmMujocoTest, SpeedLRotation) { runSpeedL(true); } + +TEST_P(MotorRobotArmMujocoTest, JointMovePRejectsInvalidTargetsAndCallbacksBeforeExecution) +{ + auto& arm = *arm_; + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const std::vector initial{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + MotionOptions options; + options.velocity = 1.0; + options.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({initial}, options).ok()); + const auto start = arm.getJointState().position; + int trajectories = 0; + options.trajectory_callback = [&](const JointTrajectory&) { ++trajectories; }; + + std::vector> invalid_targets{{}, std::vector(kDof - 1), + std::vector(kDof + 1)}; + for (const double invalid : {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), 1000.0}) { + invalid_targets.push_back(initial); + invalid_targets.back()[0] = invalid; + } + for (const auto& target : invalid_targets) { + const auto result = arm.moveP(JointPositionCommand{target}, options); + EXPECT_EQ(result.code, ArmErrorCode::InvalidArgument) << result.message; + EXPECT_FALSE(arm.busy()); + } + EXPECT_EQ(trajectories, 0); + EXPECT_LT(maxPositionError(arm.getJointState().position, start), 1e-6); + + auto target = initial; + target[0] += 0.1; + options.cancellation_requested = [] { return true; }; + EXPECT_EQ(arm.moveP(JointPositionCommand{target}, options).code, ArmErrorCode::CommandRejected); + options.cancellation_requested = {}; + int constraint_checks = 0; + options.is_tcp_pose_valid = [&](const CartesianPose&) { ++constraint_checks; return false; }; + EXPECT_FALSE(arm.moveP(JointPositionCommand{target}, options).ok()); + EXPECT_GT(constraint_checks, 0); + EXPECT_EQ(trajectories, 0); + + options.is_tcp_pose_valid = {}; + options.trajectory_callback = [&](const JointTrajectory&) { + ++trajectories; + throw std::runtime_error("injected trajectory rejection"); + }; + const auto rejected = arm.moveP(JointPositionCommand{target}, options); + EXPECT_EQ(rejected.code, ArmErrorCode::CommandFailed); + EXPECT_NE(rejected.message.find("injected trajectory rejection"), std::string::npos); + EXPECT_EQ(trajectories, 1); + EXPECT_LT(maxPositionError(arm.getJointState().position, start), 1e-6); + EXPECT_FALSE(arm.busy()); +} + +TEST_P(MotorRobotArmMujocoTest, JointAndCartesianMovePShareValidatedTrajectoryExecution) +{ + auto& arm = *arm_; + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + // Actual TouchScreenTask initialization target; preserve all seven angles. + const std::vector target{-.2423, 1.2929, 1.61, 1.58, -2.8792, .115, -.08}; + auto initial = target; + initial[0] += 0.1; + initial[3] -= 0.1; + MotionOptions options; + options.velocity = 1.0; + options.acceleration = 3.0; + ASSERT_TRUE(arm.stopMotion().ok()); + const auto initialized = arm.moveP(JointPositionCommand{initial}, options); + ASSERT_TRUE(initialized.ok()) << initialized.message; + const auto start = arm.getJointState().position; + JointTrajectory trajectory; + options.trajectory_callback = [&](const JointTrajectory& samples) { trajectory = samples; }; + const auto joint_result = arm.moveP(JointPositionCommand{target}, options); + ASSERT_TRUE(joint_result.ok()) << joint_result.message; + ASSERT_GE(trajectory.size(), 2); + EXPECT_LT(maxPositionError(trajectory.front().position, start), 1e-6); + EXPECT_LT(maxPositionError(trajectory.back().position, target), 1e-12); + EXPECT_LT(maxPositionError(arm.getJointState().position, target), 0.002); + + Eigen::Matrix4d target_transform; + ASSERT_TRUE(arm.kinematicsSolver()->fk(target, target_transform, true)); + const auto target_pose = common::math::matrixToPose(target_transform); + ASSERT_TRUE(arm.moveJ({initial}, options).ok()); + trajectory.clear(); + const auto cartesian_result = arm.moveP(target_pose, options, FrameType::Base); + ASSERT_TRUE(cartesian_result.ok()) << cartesian_result.message; + ASSERT_GE(trajectory.size(), 2); + Eigen::Matrix4d planned_transform; + ASSERT_TRUE(arm.kinematicsSolver()->fk(trajectory.back().position, planned_transform, true)); + EXPECT_LT((planned_transform.block<3, 1>(0, 3) - target_transform.block<3, 1>(0, 3)).norm(), 0.001); + EXPECT_LT(Eigen::AngleAxisd(target_transform.block<3, 3>(0, 0).transpose() * + planned_transform.block<3, 3>(0, 0)).angle(), 0.001); + EXPECT_LT(translationError(arm.getTcpPose(), target_pose), 0.001); + EXPECT_FALSE(arm.busy()); +} + +TEST_P(MotorRobotArmMujocoTest, SpeedLPlanningFailureAllowsStoppedJointReturn) +{ + if (std::string(GetParam().name) != "QpIk") GTEST_SKIP() << "hard QP failure regression"; + configureAdaptiveSpeed(false); + ASSERT_FALSE(HasFatalFailure()); + using namespace std::chrono_literals; + auto& arm = *arm_; + std::this_thread::sleep_for(300ms); + const std::vector initial{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + MotionOptions move; + move.velocity = 1.0; + move.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({initial}, move).ok()); + + // The accelerating +X command eventually needs elbow velocity outside + // its configured bounds; exercise the real QP and asynchronous executor. + CartesianVelocity target; + target.vx = 2.0; + SpeedLOptions options; + options.acceleration = 15.0; + options.linear_jerk = 100.0; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.isFault() && !arm.busy(); }, 3s); + ASSERT_TRUE(arm.isFault()); + ASSERT_FALSE(arm.busy()); + const auto planning_failure = arm.getSpeedLResult(); + ASSERT_EQ(planning_failure.code, ArmErrorCode::CommandFailed); + ASSERT_NE(planning_failure.message.find("infeasible within joint limits"), std::string::npos) + << planning_failure.message; + + const auto stopped = arm.stopMotion(); + ASSERT_TRUE(stopped.ok()) << stopped.message; + JointTrajectory return_trajectory; + move.trajectory_callback = [&](const JointTrajectory& samples) { return_trajectory = samples; }; + const auto returned = arm.moveP(JointPositionCommand{initial}, move); + ASSERT_TRUE(returned.ok()) << returned.message; + ASSERT_GE(return_trajectory.size(), 2); + EXPECT_LT(maxPositionError(return_trajectory.back().position, initial), 1e-12); + EXPECT_LT(maxPositionError(arm.getJointState().position, initial), 0.002); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.isFault()); + EXPECT_EQ(arm.getSpeedLResult().code, planning_failure.code); + EXPECT_EQ(arm.getSpeedLResult().message, planning_failure.message); + EXPECT_FALSE(arm.speedL(target, options, 0, FrameType::Base).ok()) + << "joint return must not silently acknowledge the speedL fault"; + + ASSERT_TRUE(arm.stopMotion().ok()); + const auto recovered = arm.recoverSpeedLPlanningFault(); + ASSERT_TRUE(recovered.ok()) << recovered.message; + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); + const auto restarted_from = arm.getTcpPose(); + target.vx = 0.02; + options.acceleration = 0.5; + options.linear_jerk = 10.0; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.getSpeedLCommandTwistBase().vx > 0.019 || arm.isFault(); }, 2s); + ASSERT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + EXPECT_GT(arm.getSpeedLCommandTwistBase().vx, 0.019); + std::this_thread::sleep_for(100ms); + EXPECT_GT(arm.getTcpPose().x - restarted_from.x, 0.001); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogFailureBrakesWithoutHoldingOldVelocity) +{ + runTouchLog(false); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogAdaptiveSpeedSlowsBeforeWristLimit) +{ + runTouchLog(true); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogMinimumSpeedRatioStopsAndAllowsRecovery) +{ + runTouchLog(true, .1); +} + +void MotorRobotArmMujocoTest::runTouchLog(bool adaptive, double min_speed_ratio) +{ + if (std::string(GetParam().name) != "QpIk") GTEST_SKIP() << "QP touch-log replay"; + configureAdaptiveSpeed(adaptive, min_speed_ratio); + ASSERT_FALSE(HasFatalFailure()); + using namespace std::chrono_literals; + auto& arm = *arm_; + config::TouchScreenTaskRootConfig root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (project_root_ / "cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt").string(), + &root)); + const auto& cfg = root.touch_screen_task(); + std::vector initial; + for (const auto* name : kJointNames) { + const auto& joints = cfg.initialization().joint_positions(); + const auto joint = std::find_if(joints.begin(), joints.end(), + [&](const auto& item) { return item.joint_name() == name; }); + ASSERT_NE(joint, joints.end()); + initial.push_back(joint->rad()); + } + std::this_thread::sleep_for(300ms); + ASSERT_TRUE(arm.stopMotion().ok()); + MotionOptions initialize; + initialize.velocity = cfg.initialization().velocity(); + initialize.acceleration = cfg.initialization().acceleration(); + ASSERT_TRUE(arm.moveJ({initial}, initialize).ok()); + + // Replay the rounded 2026-09-30 09:44:56 PBVS log, without camera sampling. + // T_B_G_rot is an axis-angle vector in degrees (not Euler angles). + // The original pre-approach camera pose was not logged; reconstruct its + // locked yaw from the configured initial FK and this screen-frame estimate. + const Eigen::Vector3d rotation_vector = Eigen::Vector3d(64.205, -65.0019, -72.3706) * M_PI / 180.0; + const Eigen::Matrix3d R_B_G = Eigen::AngleAxisd( + rotation_vector.norm(), rotation_vector.normalized()).toRotationMatrix(); + const auto& hand = cfg.alignment().target().hand_orientation_g(); + const Eigen::Matrix3d R_G_H = + (Eigen::AngleAxisd(hand.rz(), Eigen::Vector3d::UnitZ()) * + Eigen::AngleAxisd(hand.ry(), Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(hand.rx(), Eigen::Vector3d::UnitX())).toRotationMatrix(); + const auto& calibration = cfg.alignment().calibration().hand_tag_to_tcp(); + Eigen::Matrix3d R_H_P; + R_H_P << calibration.m00(), calibration.m01(), calibration.m02(), + calibration.m10(), calibration.m11(), calibration.m12(), + calibration.m20(), calibration.m21(), calibration.m22(); + const Eigen::Matrix3d R_target = R_G_H * R_H_P; + const Eigen::Matrix3d R_current = R_B_G.transpose() * + common::math::poseToMatrix(arm.getTcpPose()).block<3, 3>(0, 0); + Eigen::Vector3d projected = R_current.col(0) - R_target.col(2) * + R_target.col(2).dot(R_current.col(0)); + ASSERT_GT(projected.norm(), 1e-9); + projected.normalize(); + const double locked_yaw = std::atan2(R_target.col(1).dot(projected), + R_target.col(0).dot(projected)); + Eigen::Matrix4d target_B = Eigen::Matrix4d::Identity(); + target_B.block<3, 3>(0, 0) = R_B_G * R_target * + Eigen::AngleAxisd(locked_yaw, Eigen::Vector3d::UnitZ()).toRotationMatrix(); + target_B.block<3, 1>(0, 3) = Eigen::Vector3d(.544036, -.293155, -.31339); + const Eigen::Vector3d normal_B = R_B_G.col(2); + const Eigen::Vector3d anchor_B = target_B.block<3, 1>(0, 3) - + normal_B * cfg.alignment().target().position_offset_g().z(); + MotionOptions approach; + approach.velocity = cfg.approach().velocity(); + approach.acceleration = cfg.approach().acceleration(); + approach.jerk = cfg.approach().jerk(); + approach.is_tcp_pose_valid = [normal_B, anchor_B, clearance = cfg.approach().minimum_clearance_m()] + (const CartesianPose& pose) { + return normal_B.dot(Eigen::Vector3d(pose.x, pose.y, pose.z) - anchor_B) >= clearance; + }; + const auto approached = arm.moveP(common::math::matrixToPose(target_B), approach, FrameType::Base); + ASSERT_TRUE(approached.ok()) << approached.message; + const auto start_pose = arm.getTcpPose(); + const auto simulation_time = [&] { + std::lock_guard lock(world_->mutex()); + return world_->data()->time; + }; + const double start_simulation_time = simulation_time(); + const auto print_state = [&](double elapsed) { + const auto state = arm.getJointState(); + std::cout << std::setprecision(12) << "[TouchLogReplay] wall_s=" << elapsed + << " simulation_s=" << simulation_time() - start_simulation_time << " q="; + for (double q : state.position) std::cout << q << ' '; + std::cout << " qdot="; + for (double qd : state.velocity) std::cout << qd << ' '; + std::cout << std::endl; + }; + std::cout << "[TouchLogReplay] locked_yaw_rad=" << locked_yaw << std::endl; + print_state(0.0); + const auto& speed = cfg.touch().speed_l(); + SpeedLOptions options; + options.acceleration = speed.acceleration(); + options.linear_jerk = speed.linear_jerk(); + options.continuous_linear_reversal = true; + // Join the simulator's cycle barrier so no feedback sample is skipped, + // including the first failed QP cycle and the following joint braking. + const std::string probe = "touch_log_feedback_probe"; + struct ReleaseProbe { + std::shared_ptr world; + std::string name; + ~ReleaseProbe() { world->endControlCycle(name, true); } + } release{world_, probe}; + const double dt = world_->beginControlCycle(probe); + auto previous_velocity = arm.getJointState().velocity; + double maximum_acceleration = 0; + double minimum_wrist_position = std::numeric_limits::infinity(); + const auto started = std::chrono::steady_clock::now(); + ASSERT_TRUE(arm.speedL(common::math::vectorToVelocity( + common::math::toEigenVec6(speed.twist_tool())), options, 0, FrameType::Tool).ok()); + double last_command_speed = 0; + int samples = 0; + for (; samples < 3000; ++samples) { + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + const auto state = arm.getJointState(); + ASSERT_EQ(state.velocity.size(), kDof); + ASSERT_EQ(state.position.size(), kDof); + for (std::size_t joint = 0; joint < kDof; ++joint) { + maximum_acceleration = std::max(maximum_acceleration, + std::abs(state.velocity[joint] - previous_velocity[joint]) / dt); + } + previous_velocity = state.velocity; + minimum_wrist_position = std::min(minimum_wrist_position, state.position[6]); + last_command_speed = common::math::velocityToVector( + arm.getSpeedLCommandTwistBase()).head<3>().norm(); + if (samples % 100 == 0) + print_state(std::chrono::duration(std::chrono::steady_clock::now() - started).count()); + if (adaptive && min_speed_ratio > 0 && arm.isFault()) { + // A threshold stop reports failure only after measured standstill. + EXPECT_FALSE(arm.busy()); + for (double velocity : state.velocity) EXPECT_NEAR(velocity, 0, 1e-6); + } + if (arm.isFault() && !arm.busy()) break; + } + world_->endControlCycle(probe, true); + print_state(std::chrono::duration(std::chrono::steady_clock::now() - started).count()); + const auto failure = arm.getSpeedLResult(); + std::cout << "[TouchLogReplay] adaptive=" << adaptive << " result=" << failure.message + << " tcp_distance_m=" << translationError(arm.getTcpPose(), start_pose) + << " max_measured_acceleration_rad_s2=" << maximum_acceleration + << " minimum_wrist_position_rad=" << minimum_wrist_position + << " final_command_speed_m_s=" << last_command_speed << std::endl; + EXPECT_LE(maximum_acceleration, 100.01); + EXPECT_GE(minimum_wrist_position, -.57001); + RecordProperty("maximum_measured_acceleration_rad_s2", std::to_string(maximum_acceleration)); + RecordProperty("minimum_wrist_position_rad", std::to_string(minimum_wrist_position)); + RecordProperty("final_command_speed_m_s", std::to_string(last_command_speed)); + if (adaptive && min_speed_ratio == 0) { + EXPECT_EQ(samples, 3000); + EXPECT_FALSE(arm.isFault()) << failure.message; + EXPECT_TRUE(failure.ok()) << failure.message; + EXPECT_LT(last_command_speed, .035); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + } else if (adaptive) { + EXPECT_LT(samples, 3000); + EXPECT_TRUE(arm.isFault()); + EXPECT_FALSE(arm.busy()); + EXPECT_EQ(failure.code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(failure.message.find("adaptive speed ratio below min_speed_ratio"), std::string::npos); + EXPECT_NEAR(last_command_speed, 0, 1e-9); + for (double velocity : arm.getJointState().velocity) EXPECT_NEAR(velocity, 0, 1e-6); + ASSERT_TRUE(arm.stopMotion().ok()); + ASSERT_TRUE(arm.recoverSpeedLPlanningFault().ok()); + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); + const double wrist_at_stop = arm.getJointState().position[6]; + CartesianVelocity retreat; + retreat.vy = .04; + ASSERT_TRUE(arm.speedL(retreat, options, 0, FrameType::Tool).ok()); + waitFor([&] { return arm.getJointState().position[6] > wrist_at_stop + .01 || arm.isFault(); }, 2s); + EXPECT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + EXPECT_GT(arm.getJointState().position[6], wrist_at_stop + .01); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.getSpeedLResult().ok()) << arm.getSpeedLResult().message; + } else { + EXPECT_TRUE(arm.isFault()); + EXPECT_EQ(failure.code, ArmErrorCode::CommandFailed); + EXPECT_NE(failure.message.find("infeasible within joint limits"), std::string::npos); + // Before the fix the wrist held its old speed for two more ticks and + // finished at -0.569448 rad. Same-cycle braking must stop earlier. + EXPECT_GE(minimum_wrist_position, -.5693); + EXPECT_LT(minimum_wrist_position, -.54); + for (double velocity : arm.getJointState().velocity) EXPECT_NEAR(velocity, 0, 1e-6); + } + ASSERT_TRUE(arm.stopMotion().ok()); +} + +TEST_P(MotorRobotArmMujocoTest, SpeedLScalingAndRecovery) +{ + using namespace std::chrono_literals; + struct Release { + std::shared_ptr world; + std::string id; + ~Release() { world->endControlCycle(id, true); } + }; + auto& arm = *arm_; + std::this_thread::sleep_for(300ms); + MotionOptions move; + move.velocity = 1.0; + move.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}}, move).ok()); + CartesianVelocity target; + target.vx = .05; + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + options.capture_reference = true; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .05) < 1e-5; }, 2s); + const auto reference = arm.getSpeedLReference(); + ASSERT_TRUE(reference.valid); + for (const double scaling : {.5, 0.0, 1.0}) { + ASSERT_TRUE(arm.setSpeedScaling(scaling).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .05 * scaling) < 1e-5; }, 2s); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, .05 * scaling, 1e-5); + EXPECT_TRUE(arm.busy()); // A zero multiplier pauses without completing the command. + EXPECT_EQ(arm.getSpeedLReference().command_version, reference.command_version); + EXPECT_DOUBLE_EQ(arm.getSpeedLReference().tcp_pose_base.x, reference.tcp_pose_base.x); + } + EXPECT_FALSE(arm.setSpeedScaling(std::numeric_limits::quiet_NaN()).ok()); + EXPECT_DOUBLE_EQ(arm.getSpeedScaling(), 1.0); + + ASSERT_TRUE(arm.shutdown().ok()); + EXPECT_FALSE(arm.busy()); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, 0.0, 1e-12); + target.vx = -.05; + { + // Observe exactly the first restarted command before physics advances. + const std::string probe = "speedl_restart_probe"; + Release release{world_, probe}; + world_->beginControlCycle(probe); + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.getSpeedLCommandTwistBase().vx < -1e-12; }, 1s); + const auto restarted = arm.getSpeedLCommandTwistBase().vx; + EXPECT_LT(restarted, 0.0); + EXPECT_GT(restarted, -.01); // Starts from rest, not the interrupted +.05 command. + } + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 3s); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.getSpeedLResult().ok()) << arm.getSpeedLResult().message; + EXPECT_FALSE(arm.isFault()); + ASSERT_TRUE(arm.shutdown().ok()); + + target.vx = .02; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .02) < 1e-5; }, 2s); + ASSERT_TRUE(arm.protectiveStop().ok()); + EXPECT_TRUE(arm.isProtectiveStopped()); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()); + ASSERT_TRUE(arm.unlockProtectiveStop().ok()); + target.vx = -.02; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx + .02) < 1e-5; }, 2s); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, -.02, 1e-5); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 3s); + ASSERT_TRUE(arm.shutdown().ok()); + EXPECT_FALSE(arm.isFault()); + + // Hold the physics boundary while comparing the public feedback with + // MuJoCo's independent site Jacobian; the planner is idle throughout. + const std::string probe = "speedl_feedback_probe"; + Release release{world_, probe}; + world_->beginControlCycle(probe); + JointVelocityCommand joint; + joint.velocity.assign(kDof, 0.0); + joint.velocity[0] = .08; + ASSERT_TRUE(arm.speedJ(joint, 0, 0).ok()); + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + const auto state = arm.getRobotState(); + Eigen::Matrix actual = Eigen::Matrix::Zero(); + { + std::lock_guard lock(world_->mutex()); + const auto* model = world_->model(); + const auto* data = world_->data(); + const int site = mj_name2id(model, mjOBJ_SITE, "R_FINGER_TIP_SITE"); + ASSERT_GE(site, 0); + std::vector jp(3 * model->nv), jr(3 * model->nv); + mj_jacSite(model, data, jp.data(), jr.data(), site); + for (int axis = 0; axis < 3; ++axis) + for (int j = 0; j < model->nv; ++j) { + actual[axis] += jp[axis * model->nv + j] * data->qvel[j]; + actual[axis + 3] += jr[axis * model->nv + j] * data->qvel[j]; + } + } + const auto& v = state.actual_tcp_velocity; + const Eigen::Matrix reported = (Eigen::Matrix() << v.vx, v.vy, v.vz, v.wx, v.wy, v.wz).finished(); + EXPECT_LT((reported - actual).norm(), 1e-7); + EXPECT_GT(reported.norm(), .01); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, 0, 1e-12); + + std::vector> motors; + for (const auto* name : kJointNames) motors.push_back(motor_system_->getMotor(name)); + auto invalid = joint.velocity; + invalid[0] = -.08; + invalid.back() = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(motor_system_->commandCyclicVelocitiesAtomic(motors, invalid)); + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + EXPECT_NEAR(arm.getJointState().velocity[0], .08, 1e-12); // No partial write before detecting NaN. + ASSERT_TRUE(arm.stopJ(0).ok()); } INSTANTIATE_TEST_SUITE_P( diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp index 49b61bcf..004b12bf 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp @@ -20,6 +20,7 @@ #include "algorithms/kinematics/ik_solver/ik_solver_factory.h" #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -201,6 +202,8 @@ protected: { project_root_ = findProjectRoot(); ASSERT_FALSE(project_root_.empty()); + ConfigHelper::setConfigRootFromFile( + (project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string()); config::MujocoWorldRootConfig world_root_config; ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp new file mode 100644 index 00000000..a4c449f4 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp @@ -0,0 +1,357 @@ +#include "arm/motor_robot_arm/include/motor_robot_arm.h" +#include "algorithms/kinematics/ik_solver/ik_solver_factory.h" +#include "common/config/config_files.h" +#include "common/io/proto_file_io.h" +#include "common/math/transform_math.h" +#include "devices/motor/manager/include/motor_manager.h" +#include "simulate/mujoco/mujoco_viewer/include/mujoco_viewer.h" +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace cmvr::device { +namespace { +using Clock = std::chrono::steady_clock; + +struct FeedbackSample { + double time_s, sim_time_s; + std::vector position, velocity; +}; + +void writePlannedCsv(const std::filesystem::path& path, const JointTrajectory& trajectory) +{ + if (trajectory.empty()) return; + std::ofstream csv(path); + ASSERT_TRUE(csv.is_open()) << path; + csv << std::setprecision(17) << "time_s"; + for (std::size_t j = 0; j < trajectory.front().position.size(); ++j) + csv << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 << "_rad_s2,j" << j + 1 << "_rad_s3"; + csv << '\n'; + for (const auto& p : trajectory) { + ASSERT_EQ(p.acceleration.size(), p.position.size()); + ASSERT_EQ(p.jerk.size(), p.position.size()); + csv << p.time_s; + for (std::size_t j = 0; j < p.position.size(); ++j) + csv << ',' << p.position[j] << ',' << p.velocity[j] << ',' << p.acceleration[j] << ',' << p.jerk[j]; + csv << '\n'; + } + ASSERT_TRUE(csv.good()); +} + +void writeFeedbackCsv(const std::filesystem::path& path, const std::vector& samples) +{ + if (samples.empty()) return; + std::ofstream csv(path); + ASSERT_TRUE(csv.is_open()) << path; + csv << std::setprecision(17) << "time_s,sim_time_s,acceleration_time_s,jerk_time_s"; + const auto dof = samples.front().position.size(); + for (std::size_t j = 0; j < dof; ++j) + csv << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 << "_fd_rad_s2,j" << j + 1 << "_fd_rad_s3"; + csv << '\n'; + const double nan = std::numeric_limits::quiet_NaN(); + std::vector previous_acceleration(dof, nan); + double previous_acceleration_time = nan; + for (std::size_t i = 0; i < samples.size(); ++i) { + const auto& p = samples[i]; + const double dt = i ? p.time_s - samples[i - 1].time_s : nan; + const double at = i ? 0.5 * (p.time_s + samples[i - 1].time_s) : nan; + const double jt = i > 1 ? 0.5 * (at + previous_acceleration_time) : nan; + csv << p.time_s << ',' << p.sim_time_s << ',' << at << ',' << jt; + for (std::size_t j = 0; j < dof; ++j) { + const double a = i ? (p.velocity[j] - samples[i - 1].velocity[j]) / dt : nan; + const double jerk = i > 1 ? (a - previous_acceleration[j]) / (at - previous_acceleration_time) : nan; + csv << ',' << p.position[j] << ',' << p.velocity[j] << ',' << a << ',' << jerk; + previous_acceleration[j] = a; + } + previous_acceleration_time = at; + csv << '\n'; + } + ASSERT_TRUE(csv.good()); +} + +class RrtConnectMujocoTest : public ::testing::Test { +protected: + void SetUp() override + { + const std::filesystem::path root{CMVR_ES_SOURCE_DIR}; + ConfigHelper::setConfigRootFromFile((root / "cmvr-es/config/cmvr_es.pb.txt").string()); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm_mujoco.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + auto arm_config = arms.arm().robot_arms(0); + arm_config.mutable_kinematics()->mutable_pinocchio_dls_ik_solver()->set_urdf_path( + (root / "model/xiaoyan_description/dual_arm.urdf").string()); + arm_config.mutable_motion()->mutable_joint_path()->mutable_collision_checker()->set_urdf_path( + (root / "model/xiaoyan_description/dual_arm_collision.urdf").string()); + const std::vector joints(arm_config.motor().joint_names().begin(), + arm_config.motor().joint_names().end()); + + config::MujocoWorldConfig world_config; + world_config.set_id("mujoco_world"); + world_config.set_model_path((root / "model/xiaoyan_description/dual_arm.xml").string()); + world_config.set_timestep_s(0.001); + world_config.set_realtime_factor(1.0); + world_config.set_require_actuator(true); + world_ = std::make_shared(world_config); + ASSERT_TRUE(world_->init()); + // 只在仿真启动前设置初始姿态;规划后的运动通过机械臂接口执行。 + const std::vector initial{0.25, 1.0, 1.5708, 1.5708, -1.5708, 0.0, 0.0}; + ASSERT_EQ(joints.size(), initial.size()); + for (std::size_t i = 0; i < joints.size(); ++i) { + ASSERT_TRUE(world_->world()->setJointPosition(joints[i], initial[i])); + } + // 仿真关节限位可能比 URDF 更窄,规划使用两者的交集。 + auto* limits = arm_config.mutable_kinematics()->mutable_pinocchio_dls_ik_solver() + ->mutable_joint_limit_policy()->mutable_limits(); + const auto* model = world_->world()->model(); + for (auto& limit : *limits->mutable_joints()) { + const int joint = mj_name2id(model, mjOBJ_JOINT, limit.joint_name().c_str()); + ASSERT_GE(joint, 0); + limit.set_q_lb(std::max(limit.q_lb(), model->jnt_range[2 * joint])); + limit.set_q_ub(std::min(limit.q_ub(), model->jnt_range[2 * joint + 1])); + } + target_fk_ = cmvr::IKSolverFactory::create(arm_config.kinematics()); + ASSERT_TRUE(target_fk_); + ASSERT_TRUE(target_fk_->init()); + ASSERT_TRUE(world_->start()); + + config::MotorRootConfig motors; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/motor/mujoco_motors.pb.txt").string(), &motors)); + ASSERT_EQ(motors.motor().motor_groups_size(), 1); + ASSERT_EQ(motors.motor().motor_groups(0).bus_type(), config::MOTOR_BUS_MUJOCO); + motors_ = std::make_shared( + arm_config.motor().motor_system_id(), motors.motor(), "right_arm_mujoco_motors"); + ASSERT_TRUE(motors_->init()); + arm_ = std::make_shared(arm_config); + ASSERT_TRUE(arm_->init()); + ASSERT_TRUE(arm_->torqueOn().ok()); + } + + void TearDown() override + { + if (arm_) arm_->stop(); + if (motors_) motors_->stop(); + if (world_) world_->stop(); + } + + std::shared_ptr world_; + std::shared_ptr motors_; + std::shared_ptr arm_; + std::shared_ptr target_fk_; +}; + +TEST_F(RrtConnectMujocoTest, MovePWithViewer) +{ + const bool suite = std::getenv("CMVR_MOVEP_SUITE") != nullptr; + const bool headless = std::getenv("CMVR_MOVEP_HEADLESS") != nullptr; + const bool auto_close = std::getenv("CMVR_MOVEP_AUTO_CLOSE") != nullptr; + const char* output = std::getenv("CMVR_MOVEP_CSV_DIR"); + const std::filesystem::path directory = output ? output : + (std::filesystem::path(CMVR_ES_SOURCE_DIR) / "output/movep_csv").string(); + std::filesystem::create_directories(directory); + const auto names = arm_->getRobotModel().joint_names; + const auto initial = arm_->getJointState().position; + std::ofstream joint_names(directory / "joints.csv"); + joint_names << "index,name\n"; + std::vector q_indices, v_indices; + for (std::size_t j = 0; j < names.size(); ++j) { + joint_names << j + 1 << ',' << names[j] << '\n'; + const int id = mj_name2id(world_->world()->model(), mjOBJ_JOINT, names[j].c_str()); + ASSERT_GE(id, 0); + q_indices.push_back(world_->world()->model()->jnt_qposadr[id]); + v_indices.push_back(world_->world()->model()->jnt_dofadr[id]); + } + struct Target { const char* name; std::vector joints; CartesianPose pose; }; + struct Profile { const char* name; double velocity, acceleration, jerk; }; + std::vector targets{ + {"joint_pose_1", {-0.446719, -0.013159, 2.513135, 1.522461, -0.638216, 0.254061, -0.2}, {}}, + {"joint_pose_2", {-0.557132, 1.234893, 1.293086, 1.99, -1.833259, -0.595983, 0.422149}, {}}, + {"joint_pose_3", {-0.524703, 0.407224, 1.582127, 0.663140, -0.736188, 0.154737, -0.2}, {}}, + {"joint_pose_4", {0.710814, 0.438574, 0.687546, 1.99, -1.031896, 0.72, 0.179214}, {}}, + {"joint_pose_5", {0.497175, 1.411030, 2.583072, 1.645615, -1.950738, -0.72, 0.825329}, {}}, + {"joint_pose_6", {0.694478, 1.237590, 2.214783, 1.99, -0.669084, 0.72, -0.2}, {}}, + {"joint_pose_7", {-0.549076, 1.51, 2.525787, 1.551384, -0.523898, -0.72, -0.061424}, {}}, + {"joint_pose_8", {0.197744, 1.51, 2.622572, 0.913252, -2.040164, 0.254035, 0.967050}, {}}}; + if (!suite) targets.resize(1); + std::vector profiles{{"v065_a170_j030", 0.65, 1.7, 30.0}}; + if (suite) { + if (!std::getenv("CMVR_MOVEP_PROBE")) + profiles = {{"v030_a080_j030", 0.30, 0.8, 30.0}, {"v065_a080_j030", 0.65, 0.8, 30.0}, + {"v030_a170_j030", 0.30, 1.7, 30.0}, {"v065_a170_j030", 0.65, 1.7, 30.0}, + {"v065_a170_j001", 0.65, 1.7, 1.0}, {"v065_a170_j005", 0.65, 1.7, 5.0}, + {"v065_a170_j100", 0.65, 1.7, 100.0}}; + } + Eigen::VectorXd lower, upper; + ASSERT_TRUE(target_fk_->getJointPositionLimits(lower, upper)); + for (auto& target : targets) { + ASSERT_EQ(target.joints.size(), names.size()); + for (std::size_t j = 0; j < target.joints.size(); ++j) { + ASSERT_GE(target.joints[j], lower[j]); + ASSERT_LE(target.joints[j], upper[j]); + } + // 只用候选关节角计算目标 TCP 位姿,不修改仿真或电机当前状态。 + Eigen::Matrix4d transform; + ASSERT_TRUE(target_fk_->fk(target.joints, transform, true)); + target.pose = common::math::matrixToPose(transform); + } + const auto orientation_distance = [](const CartesianPose& a, const CartesianPose& b) { + const Eigen::Matrix3d ra = common::math::poseToMatrix(a).topLeftCorner<3, 3>(); + const Eigen::Matrix3d rb = common::math::poseToMatrix(b).topLeftCorner<3, 3>(); + return Eigen::AngleAxisd(ra.transpose() * rb).angle(); + }; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_->world()); + viewer->setupCamera(2.5, -160.0, -20.0); + viewer->setRunning(true); + } + std::atomic closed{false}; + std::thread motion([&] { + if (!headless) std::this_thread::sleep_for(std::chrono::seconds(2)); + std::ofstream summary(directory / "cases.csv"); + summary << std::setprecision(17) + << "case,target,velocity_limit,acceleration_limit,jerk_limit,dx,dy,dz," + "origin_x,origin_y,origin_z,target_x,target_y,target_z,success,error_code," + "moveP_wall_s,planned_duration_s,planned_samples,feedback_samples," + "final_tcp_error_m,message,drx,dry,drz,origin_rx,origin_ry,origin_rz," + "target_rx,target_ry,target_rz,reached_x,reached_y,reached_z," + "reached_rx,reached_ry,reached_rz,requested_orientation_change_rad," + "final_orientation_error_rad"; + for (std::size_t j = 0; j < names.size(); ++j) summary << ",fk_q" << j + 1 << "_rad"; + summary << '\n'; + bool first = true; + for (const auto& candidate : targets) for (const auto& profile : profiles) { + if (closed.load()) return; + // 每次经机械臂接口回到同一关节起点,避免不同试验的 IK 种子漂移。 + const auto current = arm_->getJointState().position; + double return_distance = 0.0; + for (std::size_t j = 0; j < initial.size(); ++j) + return_distance = std::max(return_distance, std::abs(current[j] - initial[j])); + if (!first && return_distance > 1e-6) { + MotionOptions reset; + reset.velocity = 0.65; reset.acceleration = 1.7; reset.jerk = 30.0; + reset.cancellation_requested = [&] { return closed.load(); }; + const auto returned = arm_->moveJ(JointPositionCommand{initial}, reset); + if (!returned.ok()) { + ADD_FAILURE() << "return to start failed: " << returned.message; + if (viewer) viewer->requestStop(); + return; + } + } + first = false; + const CartesianPose origin = arm_->fk(true); + const CartesianPose target = candidate.pose; + const double dx = target.x - origin.x, dy = target.y - origin.y, dz = target.z - origin.z; + const double orientation_change = orientation_distance(origin, target); + EXPECT_GT(std::hypot(std::hypot(dx, dy), dz), 0.001); + EXPECT_GT(orientation_change, 1e-3); + const std::string id = std::string(candidate.name) + "_" + profile.name; + JointTrajectory planned; + std::vector feedback; + feedback.reserve(20000); + std::atomic capturing{false}, finished{false}; + Clock::time_point epoch; + std::thread recorder([&] { + auto next = Clock::now(); + double last_sim_time = -1.0; + while (!finished.load()) { + if (capturing.load()) { + FeedbackSample sample; + sample.position.resize(names.size()); + sample.velocity.resize(names.size()); + { + // 同一仿真步的 q/v 快照;DirectState 模式下不用 qacc 当作实际加速度。 + std::lock_guard lock(world_->world()->mutex()); + const auto* data = world_->world()->data(); + sample.time_s = std::chrono::duration(Clock::now() - epoch).count(); + sample.sim_time_s = data->time; + for (std::size_t j = 0; j < names.size(); ++j) { + sample.position[j] = data->qpos[q_indices[j]]; + sample.velocity[j] = data->qvel[v_indices[j]]; + } + } + if (sample.sim_time_s > last_sim_time) { + last_sim_time = sample.sim_time_s; + feedback.push_back(std::move(sample)); + } + } + next = std::max(next + std::chrono::milliseconds(1), Clock::now()); + std::this_thread::sleep_until(next); + } + }); + MotionOptions options; + options.velocity = profile.velocity; + options.acceleration = profile.acceleration; + options.jerk = profile.jerk; + options.cancellation_requested = [&] { return closed.load(); }; + options.trajectory_callback = [&](const JointTrajectory& trajectory) { + planned = trajectory; + epoch = Clock::now(); // 执行前轨迹回调完成时刻,不额外对齐或平移反馈曲线。 + capturing.store(true); + }; + std::cout << "[MovePCase] begin " << id + << " translation_m=" << std::hypot(std::hypot(dx, dy), dz) + << " rotation_rad=" << orientation_change << std::endl; + const auto begin = Clock::now(); + const auto result = arm_->moveP(target, options, FrameType::Base); + const double elapsed = std::chrono::duration(Clock::now() - begin).count(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + finished.store(true); + recorder.join(); + writePlannedCsv(directory / (id + "_planned.csv"), planned); + writeFeedbackCsv(directory / (id + "_actual.csv"), feedback); + const auto reached = arm_->fk(true); + const double error = std::hypot(std::hypot(reached.x - target.x, reached.y - target.y), reached.z - target.z); + const double orientation_error = orientation_distance(reached, target); + summary << id << ',' << candidate.name << ',' << options.velocity << ',' << options.acceleration + << ',' << options.jerk << ',' << dx << ',' << dy << ',' << dz + << ',' << origin.x << ',' << origin.y << ',' << origin.z + << ',' << target.x << ',' << target.y << ',' << target.z + << ',' << result.ok() << ',' << static_cast(result.code) << ',' << elapsed + << ',' << (planned.empty() ? 0.0 : planned.back().time_s) + << ',' << planned.size() << ',' << feedback.size() << ',' << error + << ',' << std::quoted(result.message) + << ',' << target.rx - origin.rx << ',' << target.ry - origin.ry << ',' << target.rz - origin.rz + << ',' << origin.rx << ',' << origin.ry << ',' << origin.rz + << ',' << target.rx << ',' << target.ry << ',' << target.rz + << ',' << reached.x << ',' << reached.y << ',' << reached.z + << ',' << reached.rx << ',' << reached.ry << ',' << reached.rz + << ',' << orientation_change << ',' << orientation_error; + for (const double q : candidate.joints) summary << ',' << q; + summary << '\n'; + summary.flush(); + std::cout << "[MovePCase] end " << id << " success=" << result.ok() + << " position_error_m=" << error << " orientation_error_rad=" << orientation_error + << " message=" << result.message << " csv=" << directory << std::endl; + if (!closed.load()) { + EXPECT_TRUE(result.ok()) << id << ": " << result.message; + if (result.ok()) { + EXPECT_LT(error, 0.002) << id; + EXPECT_LT(orientation_error, 0.005) << id; + } + } + } + if (auto_close || headless) if (viewer) viewer->requestStop(); + }); + if (!headless) { + viewer->run(); + closed.store(true); + } + motion.join(); +} + +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp new file mode 100644 index 00000000..514faf43 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp @@ -0,0 +1,636 @@ +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" + +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" +#include "common/config/config_files.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { +namespace { + +SpeedLExecutor::Config normalizeConfig(SpeedLExecutor::Config config) +{ + const SpeedLExecutor::Config defaults; + using cmvr::common::config::positiveOr; + config.control_period_s = positiveOr(config.control_period_s, defaults.control_period_s); + config.stop_twist_norm = positiveOr(config.stop_twist_norm, defaults.stop_twist_norm); + config.stop_command_velocity_norm = positiveOr(config.stop_command_velocity_norm, defaults.stop_command_velocity_norm); + config.stop_measured_velocity_norm = positiveOr(config.stop_measured_velocity_norm, defaults.stop_measured_velocity_norm); + config.stop_acceleration = positiveOr(config.stop_acceleration, defaults.stop_acceleration); + config.stop_timeout_s = positiveOr(config.stop_timeout_s, defaults.stop_timeout_s); + return config; +} + +Result callbackException(const char* operation) +{ + try { + throw; + } catch (const std::exception& error) { + return Result::failure(ArmErrorCode::CommandFailed, std::string(operation) + ": " + error.what()); + } catch (...) { + return Result::failure(ArmErrorCode::CommandFailed, std::string(operation) + ": unknown exception"); + } +} + +// Release a failed simulation cycle before recovery attempts another one. +struct CycleGuard { + const SpeedLExecutor::EndCycleCallback& end; + Result& status; + bool& computation_result; + bool active{false}; + ~CycleGuard() + { + if (!active) return; + try { + end(false); + } catch (...) { + computation_result = false; + const auto error = callbackException("end speedL cycle"); + if (status.ok()) status = error; + else status.message += "; " + error.message; + } + } +}; + +} // namespace + +SpeedLExecutor::SpeedLExecutor( + Config config, std::shared_ptr planner, + const std::size_t dof, ReadStateCallback read_state, + SendVelocityCallback send_velocity, ReadScalingCallback read_scaling, + BeginCycleCallback begin_cycle, EndCycleCallback end_cycle) + : config_(normalizeConfig(config)), planner_(std::move(planner)), dof_(dof), + read_state_(std::move(read_state)), send_velocity_(std::move(send_velocity)), + read_scaling_(std::move(read_scaling)), begin_cycle_(std::move(begin_cycle)), + end_cycle_(std::move(end_cycle)) +{ +} + +SpeedLExecutor::~SpeedLExecutor() +{ + (void)shutdown(); +} + +Result SpeedLExecutor::speedL(const CartesianVelocity& velocity, + const SpeedLOptions& options, + const double duration, const FrameType frame) +{ + if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 || + static_cast(begin_cycle_) != static_cast(end_cycle_) || + !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) || + (frame != FrameType::Base && frame != FrameType::Tool) || + (options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input"); + } + std::uint64_t version; + { + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + if (faulted_.load()) { + return Result::failure(ArmErrorCode::RobotInFault, + "speedL fault must be cleared: " + last_result_.message); + } + if (!pending_stop_reason_.ok()) { + return Result::failure(ArmErrorCode::RobotNotReady, + "speedL is stopping: " + pending_stop_reason_.message); + } + if (finishing_) { + return Result::failure(ArmErrorCode::RobotNotReady, "speedL is confirming stop"); + } + if (!command_active_) { + reset_required_ = true; + last_result_ = Result::success(); + } + target_twist_ = velocity; + target_frame_ = frame; + target_options_ = options; + reference_ = {}; + command_active_ = true; + busy_.store(true); + version = ++command_version_; + if (!worker_.joinable()) { + stop_requested_.store(false); + shutdown_result_ = Result::success(); + try { + worker_ = std::thread(&SpeedLExecutor::workerLoop_, this); + } catch (...) { + command_active_ = false; + busy_.store(false); + return callbackException("start speedL worker"); + } + } + } + cv_.notify_all(); + + if (duration > 0.0) { + std::this_thread::sleep_for(std::chrono::duration(duration)); + { + std::lock_guard lock(mutex_); + // Scaling updates do not replace the command or restart its timer. + if (command_active_ && command_version_ == version && !faulted_.load() && + pending_stop_reason_.ok()) { + setStopTargetLocked_(target_options_.acceleration); + } + } + cv_.notify_all(); + return lastResult(); + } + return Result::success(); +} + +Result SpeedLExecutor::stop(const std::optional acceleration) +{ + const double value = acceleration.value_or(config_.stop_acceleration); + if (!std::isfinite(value) || value <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "stop acceleration must be positive and finite"); + } + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + // A faulted active command is already braking. Accept an idempotent stop + // without replacing that phase or hiding its separately queryable error. + if (faulted_.load()) return command_active_ ? Result::success() : last_result_; + if (!pending_stop_reason_.ok()) return Result::success(); + if (!command_active_) return Result::success(); + setStopTargetLocked_(value); + cv_.notify_all(); + return Result::success(); +} + +Result SpeedLExecutor::shutdown() +{ + std::lock_guard lifecycle(lifecycle_mutex_); + if (worker_.joinable()) { + stop_requested_.store(true); + cv_.notify_all(); + worker_.join(); + stop_requested_.store(false); + std::lock_guard lock(mutex_); + return shutdown_result_; + } + if (busy_.load()) { + { + std::lock_guard lock(mutex_); + finishing_ = true; + } + finishCommand_(); + } + std::lock_guard lock(mutex_); + return shutdown_result_; +} + +Result SpeedLExecutor::clearFault() +{ + return clearFault_(false); +} + +Result SpeedLExecutor::clearPlanningFault() +{ + return clearFault_(true); +} + +void SpeedLExecutor::recordStopFailure(const Result& result) +{ + if (result.ok()) return; + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + recordFailureLocked_(result); +} + +Result SpeedLExecutor::clearFault_(const bool planning_only) +{ + std::lock_guard lifecycle(lifecycle_mutex_); + const auto explicit_recovery = [&] { + return Result::failure(ArmErrorCode::RobotInFault, + "speedL fault requires explicit recovery: " + last_result_.message); + }; + { + std::lock_guard lock(mutex_); + if (command_active_ || finishing_) { + return Result::failure(ArmErrorCode::RobotNotReady, "speedL is still stopping"); + } + if (!faulted_.load()) return Result::success(); + if (planning_only && !planning_fault_) return explicit_recovery(); + finishing_ = true; + } + // A callback failure may have terminated the worker itself. Reap either + // an idle or exited worker before acknowledging the fault and restarting. + if (worker_.joinable()) { + stop_requested_.store(true); + cv_.notify_all(); + worker_.join(); + stop_requested_.store(false); + } + { + std::lock_guard lock(mutex_); + // Joining can expose a late callback or stop-confirmation failure. + if (planning_only && !planning_fault_) { + finishing_ = false; + return explicit_recovery(); + } + finishing_ = true; + } + const auto stopped = finish_(); + std::lock_guard lock(mutex_); + finishing_ = false; + reset_required_ = true; + busy_.store(!stopped.ok()); + shutdown_result_ = stopped; + if (!stopped.ok()) { + recordFailureLocked_(stopped); + return stopped; + } + if (planning_only) { + CMVR_LOG(INFO) << "[SpeedLExecutor] clearing stopped planning fault: " << last_result_.message; + } + faulted_.store(false); + planning_fault_ = false; + last_result_ = Result::success(); + command_twist_snapshot_ = {}; + return Result::success(); +} + +Result SpeedLExecutor::lastResult() const +{ + std::lock_guard lock(mutex_); + return last_result_; +} + +CartesianVelocity SpeedLExecutor::getCommandTwistBase() const +{ + std::lock_guard lock(mutex_); + return command_twist_snapshot_; +} + +SpeedLReference SpeedLExecutor::getReference() const +{ + std::lock_guard lock(mutex_); + return reference_; +} + +void SpeedLExecutor::workerLoop_() +{ + using Clock = std::chrono::steady_clock; + const auto period = std::chrono::duration_cast( + std::chrono::duration(config_.control_period_s)); + std::vector q_now, qd_now; + std::uint64_t submitted_version = 0, recovery_version = 0; + std::optional accepted_options; + std::optional stop_started; + auto previous_tick = Clock::now(); + bool first_tick = true; + bool braking = false; + + try { + while (true) { + CartesianVelocity target; + FrameType frame; + SpeedLOptions options; + std::uint64_t version; + bool reset; + bool controlled_stopping; + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [&] { return stop_requested_.load() || command_active_; }); + if (stop_requested_.load()) break; + target = target_twist_; + frame = target_frame_; + options = target_options_; + version = command_version_; + reset = reset_required_; + controlled_stopping = !pending_stop_reason_.ok(); + } + if (reset) { + accepted_options.reset(); + submitted_version = 0; + recovery_version = 0; + stop_started.reset(); + first_tick = true; + braking = false; + } + const bool stopping = braking || controlled_stopping || + twistNorm_(target) < config_.stop_twist_norm; + const auto tick = Clock::now(); + if (!stopping) stop_started.reset(); + else if (!stop_started) stop_started = tick; + double dt = first_tick ? config_.control_period_s + : std::chrono::duration(tick - previous_tick).count(); + previous_tick = tick; + first_tick = false; + CartesianVelocityStep planned; + Result status = Result::success(); + bool computation_result = false; + bool planning_result = false; + { + CycleGuard cycle{end_cycle_, status, computation_result}; + const auto emergency_zero = [&] { + computation_result = false; + CMVR_LOG(ERROR) << "[SpeedLExecutor] constrained braking failed; issuing emergency zero" + << " (acceleration/jerk not guaranteed): " << status.message; + const auto zero_result = sendVelocity_(JointVelocityCommand{std::vector(dof_, 0.0)}); + if (!zero_result.ok()) status.message += "; " + zero_result.message; + }; + try { + if (begin_cycle_) { + dt = begin_cycle_(); + cycle.active = true; + } + if (!std::isfinite(dt) || dt <= 0.0) { + status = Result::failure(ArmErrorCode::InvalidArgument, "invalid speedL cycle period"); + } else { + status = readState_(q_now, qd_now); + } + if (status.ok() && reset) { + computation_result = true; + status = planner_->reset(q_now, qd_now); + if (status.ok()) { + std::lock_guard lock(mutex_); + reset_required_ = false; + } + } + if (status.ok() && !braking && !controlled_stopping && submitted_version != version) { + computation_result = true; + status = planner_->submit(target, options, frame); + if (status.ok()) { + submitted_version = version; + accepted_options = options; + } + } + if (status.ok() && !braking) { + computation_result = false; + const double scaling = read_scaling_ ? read_scaling_() : 1.0; + if (!std::isfinite(scaling) || scaling < 0.0 || scaling > 1.0) { + status = Result::failure(ArmErrorCode::InvalidArgument, "invalid speed scaling"); + } else { + computation_result = true; + planned = planner_->step(dt, q_now, qd_now, scaling); + status = planned.status; + if (status.ok() && !planned.stop_reason.ok()) { + std::lock_guard lock(mutex_); + if (pending_stop_reason_.ok()) { + pending_stop_reason_ = planned.stop_reason; + CMVR_LOG(WARNING) << "[SpeedLExecutor] " << pending_stop_reason_.message + << "; waiting for controlled stop"; + } + controlled_stopping = true; + if (!stop_started) stop_started = tick; + } + planning_result = status.code == ArmErrorCode::CommandFailed || + status.code == ArmErrorCode::OutOfJointLimit || + status.code == ArmErrorCode::OutOfVelocityLimit || + status.code == ArmErrorCode::OutOfAccelerationLimit || + status.code == ArmErrorCode::OutOfWorkspace; + if (planning_result && !stop_requested_.load()) { + std::lock_guard lock(mutex_); + if (controlled_stopping || command_version_ == version) { + CMVR_LOG(ERROR) << "[SpeedLExecutor] " << status.message + << "; starting joint braking in the failed cycle"; + recordFailureLocked_(status, true); + braking = true; + if (!stop_started) stop_started = tick; + } + } + } + } + if (braking && (status.ok() || (computation_result && planning_result)) && + !stop_requested_.load()) { + // Use the feedback from this acquired cycle: never release + // the failed cycle while the previous speed is still held. + computation_result = false; + planning_result = false; + planned = planner_->brakeStep(dt, q_now, qd_now); + status = planned.status; + } + if (status.ok() && !stop_requested_.load()) { + computation_result = false; + status = sendVelocity_(planned.joint_velocity); + if (status.ok()) planner_->commitStep(); + } + if ((braking || controlled_stopping) && !status.ok() && + !stop_requested_.load()) emergency_zero(); + } catch (...) { + computation_result = false; + status = callbackException("speedL cycle"); + if ((braking || controlled_stopping) && !stop_requested_.load()) emergency_zero(); + } + } + // A requested hard stop owns subsequent output; its safety rejection + // must not become an unrelated asynchronous motion error. + if (stop_requested_.load()) { + if (!status.ok()) { + std::lock_guard lock(mutex_); + if (status.code == ArmErrorCode::RobotInEmergencyStop || + status.code == ArmErrorCode::RobotInProtectiveStop) { + planning_fault_ = false; + if (!pending_stop_reason_.ok()) recordFailureLocked_(status); + } else { + recordFailureLocked_(status, computation_result && planning_result); + } + } + break; + } + bool finish = false; + const bool stop_timed_out = stop_started && + std::chrono::duration(Clock::now() - *stop_started).count() >= config_.stop_timeout_s; + { + std::lock_guard lock(mutex_); + // A replacement makes an old computation irrelevant, but does + // not repair failed feedback, output, scaling or clock I/O. + const bool external_stop = status.code == ArmErrorCode::RobotInEmergencyStop || + status.code == ArmErrorCode::RobotInProtectiveStop; + const bool applies = braking || controlled_stopping || command_version_ == version || + (!status.ok() && !computation_result); + if (external_stop) { + // Safety flags can be raised before shutdown reaches this + // executor. Their rejection is an intentional hard stop. + planning_fault_ = false; + if (controlled_stopping) recordFailureLocked_(status); + command_active_ = false; + finishing_ = true; + finish = true; + } else if (applies && stop_timed_out) { + recordFailureLocked_(status, computation_result && planning_result); + recordFailureLocked_(Result::failure(ArmErrorCode::Timeout, + "speedL smooth stop timed out")); + command_active_ = false; + finishing_ = true; + finish = true; + } else if (applies && !status.ok()) { + CMVR_LOG(ERROR) << "[SpeedLExecutor] " << status.message; + recordFailureLocked_(status, computation_result && planning_result); + if (!braking && !controlled_stopping && accepted_options && + command_version_ != recovery_version) { + target_options_ = *accepted_options; + setStopTargetLocked_(accepted_options->acceleration); + recovery_version = command_version_; + } else { + command_active_ = false; + finishing_ = true; + finish = true; + } + } else if (applies) { + command_twist_snapshot_ = planned.twist_base; + if (planned.reference.valid) { + planned.reference.command_version = version; + reference_ = planned.reference; + } + if ((stopping || braking || controlled_stopping) && planned.settled && + velocityNorm_(planned.joint_velocity.velocity) < config_.stop_command_velocity_norm && + velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) { + command_active_ = false; + finishing_ = true; + finish = true; + } + } + } + if (finish) { + finishCommand_(); + first_tick = true; + } + if (!begin_cycle_) { + // Never replay late deadlines in a burst. Integrate the measured + // interval on the next cycle instead of using a fictitious clock. + auto deadline = tick + period; + if (Clock::now() >= deadline) deadline = Clock::now() + period; + std::unique_lock lock(mutex_); + cv_.wait_until(lock, deadline, [&] { return stop_requested_.load(); }); + } + } + } catch (...) { + const auto error = callbackException("speedL worker"); + std::lock_guard lock(mutex_); + recordFailureLocked_(error); + } + bool needs_stop; + { + std::lock_guard lock(mutex_); + needs_stop = command_active_ || busy_.load(); + command_active_ = false; + finishing_ = needs_stop; + reset_required_ = true; + } + if (needs_stop) finishCommand_(); +} + +void SpeedLExecutor::setStopTargetLocked_(const double acceleration) +{ + target_twist_ = {}; + target_frame_ = FrameType::Base; + target_options_.acceleration = acceleration; + target_options_.capture_reference = false; + command_active_ = true; + ++command_version_; +} + +void SpeedLExecutor::recordFailureLocked_(const Result& result, const bool planning_failure) +{ + if (result.ok()) return; + if (!pending_stop_reason_.ok()) { + const auto reason = std::exchange(pending_stop_reason_, Result::success()); + recordFailureLocked_(reason, true); + } + planning_fault_ = faulted_.load() ? planning_fault_ && planning_failure : planning_failure; + faulted_.store(true); + if (last_result_.ok()) last_result_ = result; + else if (last_result_.message.find(result.message) == std::string::npos) + last_result_.message += "; " + result.message; +} + +void SpeedLExecutor::finishCommand_() +{ + const auto stopped = finish_(); + std::lock_guard lock(mutex_); + shutdown_result_ = stopped; + if (!pending_stop_reason_.ok()) { + const auto reason = std::exchange(pending_stop_reason_, Result::success()); + recordFailureLocked_(reason, true); + } + recordFailureLocked_(stopped); + reset_required_ = true; + finishing_ = false; + if (stopped.ok()) command_twist_snapshot_ = {}; + busy_.store(!stopped.ok()); +} + +Result SpeedLExecutor::finish_() +{ + JointVelocityCommand zero; + zero.velocity.assign(dof_, 0.0); + auto result = sendVelocity_(zero); + // Simulation must be released before waiting for measured stop, including + // when zero submission failed and needs an explicit later recovery. + if (end_cycle_) { + try { + end_cycle_(true); + } catch (...) { + const auto error = callbackException("finish speedL cycle"); + if (result.ok()) result = error; + else result.message += "; " + error.message; + } + } + if (!result.ok()) return result; + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::duration(config_.stop_timeout_s); + std::vector q, qd; + while (true) { + result = readState_(q, qd); + if (!result.ok()) return result; + if (velocityNorm_(qd) < config_.stop_measured_velocity_norm) return Result::success(); + if (std::chrono::steady_clock::now() >= deadline) { + return Result::failure(ArmErrorCode::Timeout, "speedL zero sent but measured stop was not confirmed"); + } + std::this_thread::sleep_for(std::chrono::duration(config_.control_period_s)); + } +} + +Result SpeedLExecutor::readState_(std::vector& q, std::vector& qd) const +{ + try { + if (!read_state_ || !read_state_(q, qd)) { + return Result::failure(ArmErrorCode::CommandFailed, "speedL read_state failed"); + } + if (q.size() != dof_ || qd.size() != dof_ || + !std::all_of(q.begin(), q.end(), [](double value) { return std::isfinite(value); }) || + !std::all_of(qd.begin(), qd.end(), [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid state feedback"); + } + return Result::success(); + } catch (...) { + return callbackException("speedL read_state"); + } +} + +Result SpeedLExecutor::sendVelocity_(const JointVelocityCommand& velocity) const +{ + try { + if (!send_velocity_) return Result::failure(ArmErrorCode::RobotNotReady, "speedL has no velocity output"); + if (velocity.velocity.size() != dof_ || + !std::all_of(velocity.velocity.begin(), velocity.velocity.end(), + [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid joint velocity command"); + } + return send_velocity_(velocity); + } catch (...) { + return callbackException("speedL send_velocity"); + } +} + +double SpeedLExecutor::velocityNorm_(const std::vector& velocity) +{ + double value = 0.0; + for (const double item : velocity) value = std::hypot(value, item); + return value; +} + +double SpeedLExecutor::twistNorm_(const CartesianVelocity& velocity) +{ + return common::math::velocityToVector(velocity).norm(); +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp new file mode 100644 index 00000000..c7817af4 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp @@ -0,0 +1,1031 @@ +#include +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" +#include +#include +#include +#include +#include +#include +#include + +namespace cmvr::device { +namespace { +using namespace std::chrono_literals; +class Planner final : public CartesianVelocityPlanner { +public: + bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; } + Result reset(const std::vector&, const std::vector& qd) override { + if (!check("reset")) return Result::failure(ArmErrorCode::CommandFailed, "reset failed"); + current = {}; + capture_reference = false; + reset_velocity.store(qd.empty() ? 0.0 : qd.front()); + ++resets; + return Result::success(); + } + Result submit(const CartesianVelocity& target, const SpeedLOptions& options, FrameType) override { + ++submissions; + if (!check("submit")) return Result::failure(ArmErrorCode::CommandFailed, "submit failed"); + if (!accept(target, options)) return Result::failure(ArmErrorCode::InvalidArgument, "limits rejected"); + current = target; + capture_reference = options.capture_reference; + applied_reversal.store(options.continuous_linear_reversal.value_or(false)); + applied_jerk.store(options.linear_jerk.value_or(10.0)); + return Result::success(); + } + CartesianVelocityStep step(double dt, const std::vector&, const std::vector&, + double scaling = 1.0) override { + CartesianVelocityStep result; + last_period.store(dt); + last_scaling.store(scaling); + if (!check("step")) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "step failed"); + return result; + } + if (step_result) return step_result(); + result.status = Result::success(); + result.joint_velocity.velocity = {current.vy * scaling}; + result.twist_base = current; + result.twist_base.vy *= scaling; + result.settled = current.vx == 0 && current.vy == 0 && current.vz == 0 && + current.wx == 0 && current.wy == 0 && current.wz == 0 && + stop_settled.load(); + if (capture_reference) { + result.reference.valid = true; + result.reference.tcp_pose_base.y = .5; + result.reference.target_base.vx = current.vy; + capture_reference = false; + } + return result; + } + CartesianVelocityStep brakeStep(double dt, const std::vector& q, + const std::vector& qd) override { + ++brakes; + if (brake) return brake(dt, q, qd); + CartesianVelocityStep result; + result.status = Result::success(); + result.joint_velocity.velocity = {0}; + result.settled = true; + return result; + } + void commitStep() override { + check("commit"); + ++commits; + } + CartesianVelocity current; + bool capture_reference{false}; + std::atomic applied_jerk{0.0}; + std::atomic applied_reversal{false}; + std::atomic submissions{0}; + std::atomic resets{0}; + std::atomic brakes{0}, commits{0}; + std::atomic reset_velocity{0.0}; + std::atomic last_scaling{1.0}; + std::atomic last_period{0.0}; + std::atomic stop_settled{true}; + std::function check = [](auto) { return true; }; + std::function&, + const std::vector&)> brake; + std::function step_result; + std::function accept = + [](const auto&, const auto&) { return true; }; +}; + +bool waitUntil(const std::function& condition) { + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (!condition() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + return condition(); +} +TEST(SpeedLExecutor, ZeroVelocityDoesNotFinishAnUnsettledStop) { + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false, second_stop_step = false, release = false; + int stop_steps = 0; + auto planner = std::make_shared(); + planner->stop_settled = false; + planner->check = [&](std::string_view operation) { + if (operation == "step" && planner->current.vy == 0) { + std::unique_lock lock(mutex); + if (++stop_steps == 2) { + second_stop_step = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + } + return true; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + forward_sent |= command.velocity[0] > 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + } + ASSERT_TRUE(executor.stop().ok()); + { + std::unique_lock lock(mutex); + // Both commanded and measured velocities were zero on the first stop step. + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return second_stop_step; })); + EXPECT_TRUE(executor.busy()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotNotReady); + planner->stop_settled = true; + release = true; + cv.notify_all(); + } + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + EXPECT_FALSE(executor.busy()); + executor.shutdown(); +} +TEST(SpeedLExecutor, CompletedStopCannotClearNewReversal) { + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false, block_zero = false, zero_entered = false; + bool release_zero = false, reverse_sent = false; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::unique_lock lock(mutex); + forward_sent |= command.velocity[0] > 0; + reverse_sent |= command.velocity[0] < 0; + if (command.velocity[0] == 0 && block_zero && !zero_entered) { + zero_entered = true; cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release_zero; }); + } + cv.notify_all(); return Result::success(); + }); + CartesianVelocity v; v.vy = .08; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + block_zero = true; + } + ASSERT_TRUE(executor.stop(3).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; })); + } + v.vy = -.08; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + release_zero = true; cv.notify_all(); + EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; })); + } + EXPECT_TRUE(executor.busy()); + executor.shutdown(); +} +TEST(SpeedLExecutor, PublishesReferenceAfterSendAndKeepsCommandLimits) { + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand&) { + std::unique_lock lock(mutex); + if (!entered) { + entered = true; cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + return Result::success(); + }); + CartesianVelocity v; v.vy = -.08; + SpeedLOptions options; + options.acceleration = 3; + options.linear_jerk = 60; + options.continuous_linear_reversal = true; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Tool).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + EXPECT_FALSE(executor.getReference().valid); + release = true; cv.notify_all(); + } + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (!executor.getReference().valid && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + const auto ref = executor.getReference(); + EXPECT_TRUE(ref.valid); + EXPECT_GT(ref.command_version, 0U); + EXPECT_DOUBLE_EQ(ref.tcp_pose_base.y, .5); + EXPECT_DOUBLE_EQ(ref.target_base.vx, -.08); + EXPECT_DOUBLE_EQ(planner->applied_jerk.load(), 60); + EXPECT_TRUE(planner->applied_reversal.load()); + executor.shutdown(); +} +TEST(SpeedLExecutor, RejectsInvalidMotionLimitsBeforeStarting) { + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto&, auto&) { return false; }, + [](const auto&) { return Result::success(); }); + SpeedLOptions options; + options.linear_jerk = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(executor.speedL({}, options, 0, FrameType::Base).ok()); + options.linear_jerk = -1; + EXPECT_FALSE(executor.speedL({}, options, 0, FrameType::Base).ok()); + EXPECT_FALSE(executor.busy()); +} + +TEST(SpeedLExecutor, FailedOldCommandCannotClearNewCommand) { + // A superseded computation may be discarded. Actual I/O failures must + // remain visible even if a newer command arrived while I/O was pending. + for (const auto stage : {"submit", "step"}) { + SCOPED_TRACE(stage); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false, reverse_sent = false; + auto gate = [&](std::string_view operation) { + std::unique_lock lock(mutex); + if (operation != stage || entered) return true; + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + return false; + }; + auto planner = std::make_shared(); + planner->check = gate; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {0}; return gate("read"); }, + [&](const JointVelocityCommand& command) { + if (!gate("send")) return Result::failure(ArmErrorCode::CommandFailed, "injected failure"); + std::lock_guard lock(mutex); + reverse_sent |= command.velocity[0] < 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(target, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.08; + SpeedLOptions reverse_options; + reverse_options.acceleration = 3; + ASSERT_TRUE(executor.speedL(target, reverse_options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + release = true; + cv.notify_all(); + EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; })); + } + EXPECT_TRUE(executor.busy()); + executor.shutdown(); + } +} + +TEST(SpeedLExecutor, TimedCommandStopsAndIdleStopDoesNotRestartWorker) { + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(executor.speedL(target, options, .05, FrameType::Base).ok()); + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + ASSERT_FALSE(executor.busy()); + EXPECT_DOUBLE_EQ(executor.getCommandTwistBase().vy, 0); + EXPECT_EQ(planner->submissions.load(), 2); // start and timed stop, not every cycle + ASSERT_TRUE(executor.stop().ok()); + EXPECT_FALSE(executor.busy()); + EXPECT_EQ(planner->submissions.load(), 2); + // A completed command leaves a reusable worker; shutdown may start a new one. + executor.shutdown(); + ASSERT_TRUE(executor.speedL(target, options, .05, FrameType::Base).ok()); + executor.shutdown(); + EXPECT_FALSE(executor.busy()); +} + +TEST(SpeedLExecutor, RejectedLimitsStopWithLastAcceptedOptionsAndRetryOnlyOnce) { + for (bool rejected_stop : {false, true}) { + for (bool recovery_fails : {false, true}) { + SCOPED_TRACE(::testing::Message() << "rejected_stop=" << rejected_stop + << " recovery_fails=" << recovery_fails); + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false; + std::vector targets; + std::vector requests; + auto planner = std::make_shared(); + planner->accept = [&](const CartesianVelocity& target, const SpeedLOptions& options) { + std::lock_guard lock(mutex); + targets.push_back(target); + requests.push_back(options); + return options.linear_jerk != .01 && !(recovery_fails && target.vy == 0); + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + forward_sent |= command.velocity[0] > 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions accepted; + accepted.acceleration = 3; + accepted.linear_jerk = 10; + accepted.continuous_linear_reversal = true; + ASSERT_TRUE(executor.speedL(target, accepted, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + } + SpeedLOptions rejected = accepted; + rejected.acceleration = .1; + rejected.linear_jerk = .01; + rejected.continuous_linear_reversal = false; + rejected.capture_reference = true; + target.vy = rejected_stop ? 0 : -.08; + ASSERT_TRUE(executor.speedL(target, rejected, 0, FrameType::Base).ok()); + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + ASSERT_FALSE(executor.busy()); + EXPECT_TRUE(executor.faulted()); + EXPECT_FALSE(executor.lastResult().ok()); + { + std::lock_guard lock(mutex); + ASSERT_EQ(requests.size(), 3U); // accepted, rejected, one recovery stop + EXPECT_DOUBLE_EQ(targets.back().vy, 0); + EXPECT_DOUBLE_EQ(requests.back().acceleration, accepted.acceleration); + EXPECT_EQ(requests.back().linear_jerk, accepted.linear_jerk); + EXPECT_EQ(requests.back().continuous_linear_reversal, accepted.continuous_linear_reversal); + EXPECT_FALSE(requests.back().capture_reference); + } + executor.shutdown(); + } + } +} + +TEST(SpeedLExecutor, FailedIoLatchesFaultEvenWhenNewerCommandIsQueued) { + for (const auto stage : {"read", "send"}) { + SCOPED_TRACE(stage); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false, reverse_sent = false; + const auto gate = [&](std::string_view operation) { + std::unique_lock lock(mutex); + if (operation != stage || entered) return true; + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + return false; + }; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {0}; return gate("read"); }, + [&](const JointVelocityCommand& command) { + if (!gate("send")) + return Result::failure(ArmErrorCode::CommandFailed, "injected bus failure"); + std::lock_guard lock(mutex); + reverse_sent |= command.velocity[0] < 0; + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_FALSE(executor.lastResult().ok()); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + EXPECT_FALSE(reverse_sent); + } + executor.shutdown(); + EXPECT_TRUE(executor.faulted()); // Joining the worker does not acknowledge a fault. + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.clearFault().ok()); + EXPECT_FALSE(executor.faulted()); + } +} + +TEST(SpeedLExecutor, FailedFinalZeroStaysBusyUntilFeedbackConfirmsStop) { + auto planner = std::make_shared(); + std::atomic forward_sent{false}, allow_zero{false}; + std::atomic zero_attempts{0}; + std::atomic measured_speed{0}; + SpeedLExecutor::Config config; + config.stop_timeout_s = .03; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_speed.load()}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] != 0) forward_sent.store(true); + // The planned stop succeeds; only the final confirmation write fails. + if (command.velocity[0] == 0 && ++zero_attempts > 1 && !allow_zero.load()) + return Result::failure(ArmErrorCode::CommandFailed, "final zero rejected"); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + ASSERT_TRUE(executor.stop().ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted(); })); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.lastResult().ok()); + EXPECT_FALSE(executor.shutdown().ok()); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.clearFault().ok()); + allow_zero.store(true); + measured_speed.store(.03); + EXPECT_FALSE(executor.clearFault().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.busy()); + measured_speed.store(0); + EXPECT_TRUE(executor.clearFault().ok()); + EXPECT_FALSE(executor.faulted()); + EXPECT_FALSE(executor.busy()); + EXPECT_TRUE(executor.lastResult().ok()); +} + +TEST(SpeedLExecutor, RestartResetsFromFeedbackAndScalingDoesNotResubmit) { + auto planner = std::make_shared(); + std::atomic scaling{1}, measured_speed{.02}; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_speed.load()}; return true; }, + [&](const auto& command) { + if (command.velocity[0] == 0) measured_speed.store(0); + return Result::success(); + }, [&] { return scaling.load(); }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(target, options, 0, FrameType::Tool).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.getReference().valid; })); + EXPECT_EQ(planner->resets.load(), 1); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .02); + const auto reference = executor.getReference(); + for (double factor : {.5, 0.0, 1.0}) { + scaling.store(factor); + ASSERT_TRUE(waitUntil([&] { return planner->last_scaling.load() == factor; })); + EXPECT_TRUE(executor.busy()); + EXPECT_EQ(planner->submissions.load(), 1); + EXPECT_EQ(planner->resets.load(), 1); + EXPECT_EQ(executor.getReference().command_version, reference.command_version); + EXPECT_DOUBLE_EQ(executor.getReference().target_base.vx, reference.target_base.vx); + } + ASSERT_TRUE(executor.shutdown().ok()); + measured_speed.store(.004); + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return planner->resets.load() == 2; })); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .004); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, DelayedCycleDoesNotBurstCatchUpCommands) { + auto planner = std::make_shared(); + int steps = 0; + planner->check = [&](std::string_view operation) { + if (operation == "step" && ++steps == 2) std::this_thread::sleep_for(40ms); + return true; + }; + std::mutex mutex; + std::condition_variable cv; + std::vector sends; + SpeedLExecutor::Config config; + config.control_period_s = .01; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] > 0) { + std::lock_guard lock(mutex); + sends.push_back(std::chrono::steady_clock::now()); + cv.notify_all(); + } + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return sends.size() >= 5; })); + for (std::size_t i = 2; i < 5; ++i) + EXPECT_GE(std::chrono::duration(sends[i] - sends[i - 1]).count(), .005); + } + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ExternalClockIsReleasedOnStopShutdownAndPlanningFailure) { + for (const auto ending : {"stop", "shutdown", "failure"}) { + SCOPED_TRACE(ending); + auto planner = std::make_shared(); + std::atomic fail{false}; + planner->check = [&](std::string_view operation) { return operation != "step" || !fail.load(); }; + std::atomic continued_cycles{0}, finished_cycles{0}; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }, {}, + [] { std::this_thread::sleep_for(2ms); return .002; }, + [&](bool finished) { if (finished) ++finished_cycles; else ++continued_cycles; }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return continued_cycles.load() >= 2; })); + EXPECT_DOUBLE_EQ(planner->last_period.load(), .002); + if (std::string_view(ending) == "failure") fail.store(true); + else if (std::string_view(ending) == "stop") EXPECT_TRUE(executor.stop().ok()); + else EXPECT_TRUE(executor.shutdown().ok()); + ASSERT_TRUE(waitUntil([&] { return finished_cycles.load() > 0; })); + EXPECT_TRUE(waitUntil([&] { return !executor.busy(); })); + if (std::string_view(ending) == "failure") EXPECT_TRUE(executor.faulted()); + executor.shutdown(); + } +} + +TEST(SpeedLExecutor, FailedCycleBrakesBeforeReleaseAndKeepsOriginalFaultUntilStopped) { + auto planner = std::make_shared(); + std::mutex mutex; + std::condition_variable cv; + std::vector failure_cycle; + bool release = false, second_brake_entered = false; + std::atomic cycle{0}, first_brake_cycle{0}; + double measured = .03, sent = .03; + planner->check = [&](std::string_view operation) { + std::lock_guard lock(mutex); + if (operation == "step") { + first_brake_cycle.store(cycle.load()); + failure_cycle.emplace_back("failed step"); + return false; + } + if (operation == "commit" && cycle == first_brake_cycle) + failure_cycle.emplace_back("commit"); + return true; + }; + planner->brake = [&](double, const auto&, const auto& qd) { + std::unique_lock lock(mutex); + if (planner->brakes == 1) failure_cycle.emplace_back("brake"); + if (planner->brakes == 2) { + second_brake_entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + CartesianVelocityStep result; + result.status = Result::success(); + const double next = std::max(0.0, qd.front() - .01); + result.joint_velocity.velocity = {next}; + result.settled = next == 0; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { + std::lock_guard lock(mutex); + q = {0}; qd = {measured}; return true; + }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + sent = command.velocity.front(); + if (cycle == first_brake_cycle) failure_cycle.emplace_back("send brake"); + return Result::success(); + }, {}, + [&] { ++cycle; return .001; }, + [&](bool finished) { + std::lock_guard lock(mutex); + if (!finished && cycle == first_brake_cycle) failure_cycle.emplace_back("release"); + measured = sent; + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return second_brake_entered; })); + EXPECT_EQ(failure_cycle, (std::vector{ + "failed step", "brake", "send brake", "commit", "release"})); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.faulted()); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.stop().ok()); // Keep braking; do not replace the failed command. + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return !executor.busy(); })); + EXPECT_EQ(planner->submissions, 1); // Braking never resubmits a Cartesian zero target. + EXPECT_GE(planner->brakes, 3); + EXPECT_EQ(planner->commits, planner->brakes); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting) { + for (const bool fail_output : {false, true}) { + SCOPED_TRACE(fail_output); + auto planner = std::make_shared(); + planner->check = [](std::string_view operation) { return operation != "step"; }; + planner->brake = [&](double, const auto&, const auto&) { + CartesianVelocityStep result; + result.status = fail_output ? Result::success() + : Result::failure(ArmErrorCode::OutOfJointLimit, "braking distance exhausted"); + result.joint_velocity.velocity = {.02}; + return result; + }; + std::atomic zero_sends{0}, releases{0}; + std::atomic zero_before_release{false}; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity.front() != 0) + return Result::failure(ArmErrorCode::CommandFailed, "brake send rejected"); + ++zero_sends; + if (releases == 0) zero_before_release = true; + return Result::success(); + }, {}, [] { return .001; }, [&](bool) { ++releases; }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_TRUE(zero_before_release); + EXPECT_GE(zero_sends, 2); // Emergency output, then final stop confirmation. + EXPECT_EQ(planner->commits, 0); + EXPECT_EQ(planner->brakes, 1); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find( + fail_output ? "brake send rejected" : "braking distance exhausted"), std::string::npos); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.shutdown().ok()); + } +} + +TEST(SpeedLExecutor, UnsettledSmoothStopTimesOutAndConfirmsFinalZero) { + auto planner = std::make_shared(); + planner->stop_settled = false; + std::atomic forward_sent{false}; + std::atomic zero_sends{0}; + SpeedLExecutor::Config config; + config.stop_timeout_s = .03; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] > 0) forward_sent.store(true); + else if (command.velocity[0] == 0) ++zero_sends; + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + ASSERT_TRUE(executor.stop().ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::Timeout); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + EXPECT_GT(zero_sends.load(), 1); // Smooth-stop samples plus the final zero. + EXPECT_DOUBLE_EQ(executor.getCommandTwistBase().vy, 0); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); +} + +TEST(SpeedLExecutor, ControlledStopReportsReasonOnlyAfterMeasuredStop) { + auto planner = std::make_shared(); + std::atomic steps{0}; + std::atomic measured_velocity{.03}; + planner->step_result = [&] { + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, + "adaptive speed below minimum ratio"); + result.settled = ++steps > 1; + result.joint_velocity.velocity = {result.settled ? 0.0 : .02}; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return planner->commits >= 3; })); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.faulted()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_TRUE(executor.stop().ok()); + EXPECT_TRUE(executor.stop().ok()); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + EXPECT_EQ(executor.speedL({}, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + EXPECT_EQ(planner->submissions, 1); + EXPECT_EQ(planner->brakes, 0); + measured_velocity = 0; + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_EQ(executor.lastResult().message, "adaptive speed below minimum ratio"); + EXPECT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ControlledStopCannotBeCancelledByConcurrentReplacement) { + auto planner = std::make_shared(); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false; + std::atomic measured_velocity{.03}; + planner->step_result = [&] { + std::unique_lock lock(mutex); + if (!entered) { + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {0}; + result.settled = true; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return planner->commits >= 3; })); + EXPECT_EQ(planner->submissions, 1); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + measured_velocity = 0; + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().message, "low speed stop"); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ControlledStopPreservesReasonWhenLaterPlanningOrOutputFails) { + for (const bool fail_output : {false, true}) { + SCOPED_TRACE(fail_output); + auto planner = std::make_shared(); + int steps = 0; + std::atomic releases{0}, sends{0}; + std::atomic zero_before_failed_release{false}; + planner->step_result = [&] { + CartesianVelocityStep result; + if (++steps == 2 && !fail_output) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "stop planning failed"); + return result; + } + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {.02}; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (++sends == 2 && fail_output) + return Result::failure(ArmErrorCode::CommandFailed, "stop output failed"); + if (command.velocity[0] == 0 && releases == 1) zero_before_failed_release = true; + return Result::success(); + }, {}, [] { return .001; }, [&](bool finished) { if (!finished) ++releases; }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(executor.lastResult().message.find("low speed stop"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find( + fail_output ? "stop output failed" : "stop planning failed"), std::string::npos); + EXPECT_TRUE(zero_before_failed_release); + EXPECT_EQ(planner->brakes, fail_output ? 0 : 1); + EXPECT_EQ(planner->commits, fail_output ? 1 : 2); + const auto recovery = executor.clearPlanningFault(); + if (fail_output) EXPECT_EQ(recovery.code, ArmErrorCode::RobotInFault); + else EXPECT_TRUE(recovery.ok()); + EXPECT_TRUE(executor.shutdown().ok()); + } +} + +TEST(SpeedLExecutor, ControlledStopTimeoutPreservesReasonAndRequiresExplicitRecovery) { + auto planner = std::make_shared(); + planner->step_result = [] { + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {0}; + result.settled = false; + return result; + }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_NE(executor.lastResult().message.find("low speed stop"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find("timed out"), std::string::npos); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, PlanningFaultRecoveryConfirmsStopAndResetsNextCommand) { + auto planner = std::make_shared(); + std::atomic reject_step{true}, forward_sent{false}; + std::atomic measured_velocity{0}; + std::atomic zero_sends{0}; + planner->check = [&](std::string_view operation) { + return operation != "step" || !reject_step.load(); + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] == 0) ++zero_sends; + else forward_sent.store(true); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + const int zeros_before_clear = zero_sends.load(); + executor.recordStopFailure(Result::success()); + ASSERT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_GT(zero_sends.load(), zeros_before_clear); + EXPECT_FALSE(executor.faulted()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_EQ(planner->resets.load(), 1); + + reject_step.store(false); + measured_velocity.store(.004); + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + EXPECT_EQ(planner->resets.load(), 2); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .004); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotNotReady); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, MixedPlanningAndIoFailuresRemainIneligibleAfterSuccessfulStop) { + for (const auto stage : {"read", "send", "end", "measured_stop", "external_stop"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + std::atomic failed_step{false}, inject{true}; + planner->check = [&](std::string_view operation) { + if (operation == "step" && inject.load()) { + failed_step.store(true); + return false; + } + return true; + }; + const auto failing = [&](std::string_view operation) { + return operation == stage && failed_step.load() && inject.load(); + }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { + q = {0}; qd = {failing("measured_stop") ? .1 : 0}; + return !failing("read"); + }, + [&](const JointVelocityCommand&) { + return failing("send") ? Result::failure(ArmErrorCode::CommandFailed, "bus failed") + : Result::success(); + }, {}, [] { return .001; }, + [&](bool finished) { + if (!finished && failing("end")) throw std::runtime_error("cycle failed"); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted(); })); + // Reap the worker while injections remain active, so stop I/O and + // feedback failures have been recorded before testing recovery. + executor.shutdown(); + if (std::string_view(stage) == "external_stop") { + executor.recordStopFailure(Result::failure(ArmErrorCode::CommandRejected, "stopJ failed")); + EXPECT_NE(executor.lastResult().message.find("stopJ failed"), std::string::npos); + } + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::CommandFailed); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_FALSE(executor.busy()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.faulted()); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + EXPECT_TRUE(executor.clearFault().ok()); + } +} + +TEST(SpeedLExecutor, ExceptionsAndInvalidPlannerStateRequireExplicitRecovery) { + for (const auto stage : {"reset", "submit", "step_exception", "scaling", "period"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + std::atomic inject{true}; + planner->check = [&](std::string_view operation) { + if (!inject.load()) return true; + if (operation == "step" && std::string_view(stage) == "step_exception") + throw std::runtime_error("planner exception"); + return operation != stage; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }, + [&] { + if (inject.load() && std::string_view(stage) == "scaling") + throw std::runtime_error("scaling exception"); + return 1.0; + }, + [&] { return inject.load() && std::string_view(stage) == "period" ? 0.0 : .001; }, + [](bool) {}); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.clearFault().ok()); + } +} + +TEST(SpeedLExecutor, FailedRecoveryConfirmationPermanentlyRevokesAutomaticEligibility) { + for (const auto stage : {"read", "send", "end", "measured_stop"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + planner->check = [](std::string_view operation) { return operation != "step"; }; + std::atomic inject{false}; + const auto failing = [&](std::string_view operation) { return inject.load() && operation == stage; }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { + q = {0}; qd = {failing("measured_stop") ? .1 : 0}; + return !failing("read"); + }, + [&](const auto&) { + return failing("send") ? Result::failure(ArmErrorCode::CommandFailed, "zero failed") + : Result::success(); + }, {}, [] { return .001; }, + [&](bool finished) { + if (finished && failing("end")) throw std::runtime_error("finish failed"); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + inject.store(true); + EXPECT_FALSE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.busy()); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.clearFault().ok()); + } +} +} +} diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp index abc459b5..c8259510 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp @@ -1,4 +1,5 @@ #include "arm/motor_robot_arm/include/motor_robot_arm.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -91,6 +92,7 @@ int main(int argc, char** argv) { const auto world = world_device.world(); const int site = mj_name2id(world->model(), mjOBJ_SITE, "R_FINGER_TIP_SITE"); if (site < 0) throw std::runtime_error("TCP site not found"); + ConfigHelper::setConfigRootFromFile((root / "cmvr-es/config/cmvr_es.pb.txt").string()); auto arms = readConfig(root / "cmvr-es/config/devices/arm/arm_mujoco.pb.txt"); auto ac = arms.arm().robot_arms(0); ac.mutable_kinematics()->mutable_pinocchio_dls_ik_solver()->set_urdf_path( @@ -172,6 +174,8 @@ int main(int argc, char** argv) { require(arm.stopL(3.0)); const auto stop_deadline = Clock::now() + std::chrono::seconds(3); while (arm.busy() && Clock::now() < stop_deadline) std::this_thread::sleep_for(std::chrono::milliseconds(5)); + const bool stopped = !arm.busy(); + const double stopped_tcp_speed = sample(world, site).velocity.norm(); std::cout << std::fixed << std::setprecision(3) << "REVERSAL legacy=" << legacy << " approach_ms=" << approach_ms << " frame=" << (tool_frame ? "Tool" : "Base") @@ -184,7 +188,55 @@ int main(int argc, char** argv) { << " actual_vy_at_reverse=" << origin.velocity.dot(axis) << " max_forward_mm=" << peak * 1000 << " peak_at_ms=" << peak_ms << " actual_reverse_ms=" << reverse_ms << " return_to_origin_ms=" << return_ms - << " remained_active=" << active << " reference_valid=" << reference_valid << " csv=" << csv_path << '\n'; + << " remained_active=" << active << " reference_valid=" << reference_valid + << " stopped=" << stopped << " stopped_tcp_speed_m_s=" << stopped_tcp_speed + << " csv=" << csv_path << '\n'; + if (!stopped || stopped_tcp_speed >= .01) throw std::runtime_error("speedL did not stop cleanly"); + + CartesianPose move_l_target = arm.getTcpPose(); + move_l_target.x += .02; + MotionOptions cartesian_move; + cartesian_move.velocity = .05; + cartesian_move.acceleration = .5; + cartesian_move.jerk = 10.0; + require(arm.moveL(move_l_target, cartesian_move, FrameType::Base)); + double move_l_error = 0.0; + const auto settle_deadline = Clock::now() + std::chrono::seconds(2); + do { + const auto reached = arm.getTcpPose(); + move_l_error = Eigen::Vector3d(reached.x - move_l_target.x, + reached.y - move_l_target.y, reached.z - move_l_target.z).norm(); + if (move_l_error < .003) break; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } while (Clock::now() < settle_deadline); + if (!std::isfinite(move_l_error) || move_l_error >= .003) { + throw std::runtime_error("moveL after speedL missed its target"); + } + + const double restart_y = sample(world, site).position.y(); + CartesianVelocity restart_velocity; + restart_velocity.vy = .02; + require(arm.speedL(restart_velocity, .5, 0.0, FrameType::Base)); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const double restart_command = arm.getSpeedLCommandTwistBase().vy; + const double restart_displacement = sample(world, site).position.y() - restart_y; + require(arm.stopL(.5)); + const auto restart_stop_deadline = Clock::now() + std::chrono::seconds(3); + while (arm.busy() && Clock::now() < restart_stop_deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + const double restart_stop_speed = sample(world, site).velocity.norm(); + std::cout << "MODE_SWITCH moveL_error_mm=" << move_l_error * 1000 + << " resumed_command_vy_m_s=" << restart_command + << " resumed_displacement_y_mm=" << restart_displacement * 1000 + << " stopped=" << !arm.busy() + << " stopped_tcp_speed_m_s=" << restart_stop_speed << '\n'; + if (restart_command <= .01 || restart_displacement <= .001 || + arm.busy() || restart_stop_speed >= .01) { + throw std::runtime_error("speedL did not resume and stop after moveL"); + } + // The idle velocity worker must not overwrite the next position command. + require(arm.moveJ(JointPositionCommand{{.25, 1.0, M_PI/2, M_PI/2, -M_PI/2, 0, 0}}, move)); arm.stop(); manager->stop(); world_device.stop(); diff --git a/cmvr-es/devices/arm/robot_arm.h b/cmvr-es/devices/arm/robot_arm.h index 30bc04c8..9b885cd6 100644 --- a/cmvr-es/devices/arm/robot_arm.h +++ b/cmvr-es/devices/arm/robot_arm.h @@ -106,15 +106,32 @@ public: return speedL(velocity, options.acceleration, duration, frame); } virtual SpeedLReference getSpeedLReference() const { return {}; } + // Submission success and the asynchronous execution result are distinct. + virtual Result getSpeedLResult() const { + return Result::failure(ArmErrorCode::UnsupportedCommand, "speedL result is unavailable"); + } virtual Result stopMotion() = 0; virtual Result moveP(const CartesianPose& target, const MotionOptions& options, FrameType frame = FrameType::Base) { + if (options.is_tcp_pose_valid) { + return Result::failure( + ArmErrorCode::UnsupportedCommand, + "MoveP TCP pose constraints are not supported by this robot arm"); + } return moveL(target, options, frame); } + // Plan to the exact joint configuration without converting through FK/IK. + virtual Result moveP(const JointPositionCommand& target, + const MotionOptions& options) + { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "joint-target MoveP is not supported by this robot arm"); + } + virtual Result startServoMode(const ServoOptions& options) = 0; virtual Result servoJ(const JointPositionCommand& target) = 0; virtual Result servoL(const CartesianPose& target, @@ -132,44 +149,33 @@ public: virtual Result brakeRelease() = 0; virtual Result shutdown() = 0; virtual Result clearFault() = 0; + // Only backends that can distinguish planning faults may recover them automatically. + virtual Result recoverSpeedLPlanningFault() { + return isFault() + ? Result::failure(ArmErrorCode::RobotInFault, "arm fault requires explicit recovery") + : Result::success(); + } virtual Result unlockProtectiveStop() = 0; virtual Result loadProgram(const std::string& program_name) = 0; virtual Result playProgram() = 0; virtual Result pauseProgram() = 0; virtual Result stopProgram() = 0; - // Teaching and trajectory recording are optional vendor capabilities. - // Drivers that do not explicitly override these methods report unsupported. - virtual Result enterTeachingMode() - { - return Result::failure( - ArmErrorCode::UnsupportedCommand, - "teaching mode is not supported by this robot arm"); + // Preserve optional vendor teaching capabilities from linbo_dev. + virtual Result enterTeachingMode() { + return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm"); } - virtual Result startTrajectoryRecording(const std::string& file_name) - { - (void)file_name; - return Result::failure( - ArmErrorCode::UnsupportedCommand, - "trajectory recording is not supported by this robot arm"); + virtual Result startTrajectoryRecording(const std::string&) { + return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm"); } - virtual Result completeTeaching() - { - return Result::failure( - ArmErrorCode::UnsupportedCommand, - "complete teaching is not supported by this robot arm"); + virtual Result completeTeaching() { + return Result::failure(ArmErrorCode::UnsupportedCommand, "complete teaching is not supported by this robot arm"); } - virtual Result stopTrajectoryRecording() - { - return Result::failure( - ArmErrorCode::UnsupportedCommand, - "trajectory recording is not supported by this robot arm"); + virtual Result stopTrajectoryRecording() { + return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm"); } - virtual Result exitTeachingMode() - { - return Result::failure( - ArmErrorCode::UnsupportedCommand, - "teaching mode is not supported by this robot arm"); + virtual Result exitTeachingMode() { + return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm"); } virtual std::vector ik(const std::string& base_link, diff --git a/cmvr-es/devices/dexhand/px_6ax_gen3/README.md b/cmvr-es/devices/dexhand/px_6ax_gen3/README.md index 6b861cdf..9f4f51cf 100644 --- a/cmvr-es/devices/dexhand/px_6ax_gen3/README.md +++ b/cmvr-es/devices/dexhand/px_6ax_gen3/README.md @@ -5,18 +5,22 @@ 在仓库根目录运行: ```bash +./scripts/build.sh Debug +export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +px6_test="$PWD/build/Debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_real_test" + # 每次读取都发起一个真实请求:检查串口应答耗时和按压力值。 -./script/test_px_6ax_gen3.sh --port /dev/ttyACM0 --module-id 2 \ +"$px6_test" --port /dev/ttyACM0 --module-id 2 \ --mode sync --duration-s 30 --csv /tmp/paxini-sync.csv --raw-log /tmp/paxini-frames.log # 与触屏任务相同:后台轮询,前台读取最新有效缓存。 -./script/test_px_6ax_gen3.sh --port /dev/ttyACM0 --module-id 2 \ +"$px6_test" --port /dev/ttyACM0 --module-id 2 \ --mode stream --duration-s 30 --csv /tmp/paxini-stream.csv ``` 也可把 `--port` 指定为 `/dev/serial/by-id/` 下的稳定设备链接。设备端口取决于连接顺序;测试参数不会更改机器人部署配置里的串口。`module-id=2` 对应协议设备地址 3。 -脚本会构建真实测试并优先加载本次构建的驱动和 protobuf。默认构建目录为 `cmake-build-debug`,可用 `CMVR_BUILD_DIR` 覆盖;构建目录须已完成 CMake 配置。串口应可读写,运行测试前退出占用同一串口的程序。 +先确认构建和安装成功,再运行测试,确保 `output/lib` 中的驱动和 protobuf 与测试程序属于同一次构建。串口应可读写,运行测试前退出占用同一串口的程序。 测试期间可用手轻按、松开传感器,终端每 100 ms 显示一次力值,CSV 记录每次 getter 调用。按 Ctrl-C 可结束。CSV 的无效读数留空,不能当作零力。进程在初始化失败、没有有效数据或存在读取失败时返回非零退出码。 diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp index 726a841f..0f1d9682 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp @@ -77,7 +77,7 @@ TEST(TchlMotorRealTest, ProfilePosition) auto motor = initMotor(manager); motor->calibrateZeroQ(); if (!motor->setMode(msgs::RUN_MODE_PROFILE_POSITION) || !motor->torqueOn() || - !motor->commandProfilePosition(-6, -1, kAccelerationRadS2)) { + !motor->commandProfilePosition(3, -1, kAccelerationRadS2)) { throw std::runtime_error("Profile position command failed"); } std::cout << "target=" << kTargetPositionRad << " rad" << std::endl; diff --git a/cmvr-es/environment/CMakeLists.txt b/cmvr-es/environment/CMakeLists.txt new file mode 100644 index 00000000..b96a4097 --- /dev/null +++ b/cmvr-es/environment/CMakeLists.txt @@ -0,0 +1,13 @@ +add_library(environment SHARED src/robot_model.cpp) + +target_include_directories(environment PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_compile_definitions(environment PRIVATE + PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION + PINOCCHIO_WITH_HPP_FCL + COAL_BACKWARD_COMPATIBILITY_WITH_HPP_FCL + COAL_DISABLE_HPP_FCL_WARNINGS +) +target_link_libraries(environment PRIVATE cmvr_es::logging pinocchio_default pinocchio_parsers coal) + +add_library(cmvr_es::environment ALIAS environment) +install(TARGETS environment LIBRARY DESTINATION lib) diff --git a/cmvr-es/environment/include/robot_model.h b/cmvr-es/environment/include/robot_model.h new file mode 100644 index 00000000..0efad017 --- /dev/null +++ b/cmvr-es/environment/include/robot_model.h @@ -0,0 +1,110 @@ +#ifndef CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H +#define CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H + +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { + +using CollisionShape = coal::CollisionGeometry; + +struct CollisionBody { + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + std::size_t geometry_index{0}; + std::string name; + std::string link_name; + // Empty joint names represent the model root. + std::string joint_name; + std::string parent_joint_name; + std::shared_ptr geometry; + Eigen::Vector3d position{Eigen::Vector3d::Zero()}; + Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; + double bounding_radius_m{0.0}; +}; + +struct JointLimit { + double lower{0.0}; + double upper{0.0}; + double max_velocity{0.0}; + double max_acceleration{0.0}; + double max_torque{0.0}; +}; + +// Device metadata remains usable without a URDF. Loaded model resources are +// immutable and shared when this object is copied; live robot state is external. +struct RobotModel { + std::string name; + // Preserve linbo_dev's vendor metadata alongside the shared model. + std::string subtype; + std::string description_id; + std::string default_base_frame; + std::string default_tcp_frame; + bool detected_from_sdk{false}; + std::string manufacturer; + std::string serial_number; + std::size_t dof{0}; + std::vector joint_names; + std::vector joint_limits; + double max_tcp_speed{0.0}; + double max_tcp_acceleration{0.0}; + double max_payload{0.0}; + + bool valid() const + { + return dof > 0 && joint_names.size() == dof && + (joint_limits.empty() || joint_limits.size() == dof); + } + + // Boolean operations log errors and return false on failure. + // Loads kinematics only. Empty joint_names selects all one-DoF joints; + // otherwise the configured joint order is preserved. Limits come from URDF. + // Reloading clears previous kinematics and collision resources, even on failure. + bool loadUrdf(const std::string& path); + + // Optional collision URDF must match the loaded kinematics. A URDF without + // collision elements is accepted; an empty path explicitly clears geometry. + // Failure clears collision resources while retaining the kinematic model. + bool loadCollisionGeometry(const std::string& path); + + bool hasKinematics() const; + // Read-only backend model for IK. Missing kinematics throw; the reference + // remains valid while these loaded resources are retained by a model copy. + const pinocchio::Model& kinematics() const; + bool hasCollisionGeometry() const; + std::size_t collisionGeometryCount() const; + const std::string& urdfPath() const; + const std::string& collisionUrdfPath() const; + + // Computes root-fixed bodies and bodies attached to the active joints. + // Positions follow active_joint_names (joint_names if empty); inactive joints + // stay neutral. Missing collision geometry succeeds with an empty result. + // Invalid joint selections/positions or missing kinematics log and throw. + std::vector collisionBodies( + const std::vector& joint_positions, + const std::vector& active_joint_names = {}) const; + + // Resolve a frame rigidly attached to the model root, without live joint state. + bool fixedFramePose(const std::string& frame_name, Eigen::Isometry3d& pose) const; + bool containsName(const std::string& name) const; + +private: + static void requireMatchingKinematics(const pinocchio::Model& reference, + const pinocchio::Model& collision); + + std::string urdf_path_; + std::string collision_urdf_path_; + std::shared_ptr kinematics_; + std::shared_ptr collision_kinematics_; + std::shared_ptr collision_geometry_; +}; + +} // namespace cmvr + +#endif // CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H diff --git a/cmvr-es/environment/src/robot_model.cpp b/cmvr-es/environment/src/robot_model.cpp new file mode 100644 index 00000000..a428f085 --- /dev/null +++ b/cmvr-es/environment/src/robot_model.cpp @@ -0,0 +1,310 @@ +#include "environment/include/robot_model.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr { + +void RobotModel::requireMatchingKinematics(const pinocchio::Model& reference, + const pinocchio::Model& collision) +{ + if (reference.njoints != collision.njoints || reference.nq != collision.nq || + reference.nv != collision.nv) { + throw std::runtime_error("Collision URDF joint structure differs from kinematic URDF"); + } + for (pinocchio::JointIndex id = 1; id < collision.joints.size(); ++id) { + const auto& name = collision.names[id]; + if (!reference.existJointName(name)) { + throw std::runtime_error("Collision URDF contains an unknown joint: " + name); + } + const auto reference_id = reference.getJointId(name); + const auto& reference_joint = reference.joints[reference_id]; + auto collision_joint = collision.joints[id]; + // Compare the joint type and axis independently of parser ordering. + collision_joint.setIndexes(reference_joint.id(), reference_joint.idx_q(), + reference_joint.idx_v(), reference_joint.idx_vExtended()); + if (collision_joint != reference_joint || + collision.names[collision.parents[id]] != + reference.names[reference.parents[reference_id]] || + !collision.jointPlacements[id].isApprox(reference.jointPlacements[reference_id], 1e-9)) { + throw std::runtime_error("Collision URDF joint kinematics differ: " + name); + } + } + for (const auto& frame : collision.frames) { + if (!reference.existFrame(frame.name, frame.type)) { + // Collision-only fixed links may describe simplified geometry. + // Movable joints were already matched above. + continue; + } + const auto& reference_frame = reference.frames[reference.getFrameId(frame.name, frame.type)]; + if (collision.names[frame.parentJoint] != reference.names[reference_frame.parentJoint] || + !frame.placement.isApprox(reference_frame.placement, 1e-9)) { + throw std::runtime_error("Collision URDF frame placement differs: " + frame.name); + } + } +} + +bool RobotModel::loadUrdf(const std::string& path) +{ + auto urdf_path = path; + kinematics_.reset(); + collision_geometry_.reset(); + collision_kinematics_.reset(); + urdf_path_.clear(); + collision_urdf_path_.clear(); + try { + auto kinematics = std::make_shared(); + pinocchio::urdf::buildModel(urdf_path, *kinematics); + const auto& model = *kinematics; + + auto names = joint_names; + if (names.empty()) { + for (pinocchio::JointIndex id = 1; id < model.joints.size(); ++id) { + if (model.joints[id].nq() == 1 && model.joints[id].nv() == 1) { + names.push_back(model.names[id]); + } + } + } + std::vector limits; + limits.reserve(names.size()); + std::unordered_set unique_names; + for (const auto& joint_name : names) { + if (joint_name.empty() || !unique_names.insert(joint_name).second) { + throw std::runtime_error("Joint names must be non-empty and unique"); + } + if (!model.existJointName(joint_name)) { + throw std::runtime_error("Joint not found in URDF: " + joint_name); + } + const auto& joint = model.joints[model.getJointId(joint_name)]; + if (joint.nq() != 1 || joint.nv() != 1) { + throw std::runtime_error("Only one-DoF selected joints are supported: " + joint_name); + } + limits.push_back({model.lowerPositionLimit[joint.idx_q()], + model.upperPositionLimit[joint.idx_q()], + model.velocityLimit[joint.idx_v()], 0.0, + model.effortLimit[joint.idx_v()]}); + } + if (name.empty()) { + name = model.name; + } + dof = names.size(); + joint_names = std::move(names); + joint_limits = std::move(limits); + urdf_path_ = std::move(urdf_path); + kinematics_ = std::move(kinematics); + return true; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][loadUrdf] path=" << urdf_path << ": " << exception.what(); + return false; + } +} + +bool RobotModel::loadCollisionGeometry(const std::string& path) +{ + auto collision_path = path; + collision_geometry_.reset(); + collision_kinematics_.reset(); + collision_urdf_path_.clear(); + if (collision_path.empty()) { + return true; + } + if (!kinematics_) { + CMVR_LOG(ERROR) << "[RobotModel][loadCollisionGeometry] load robot kinematics first"; + return false; + } + try { + std::shared_ptr collision_kinematics = kinematics_; + if (collision_path != urdf_path_) { + auto model = std::make_shared(); + pinocchio::urdf::buildModel(collision_path, *model); + requireMatchingKinematics(*kinematics_, *model); + collision_kinematics = std::move(model); + } + auto geometry = std::make_shared(); + pinocchio::urdf::buildGeom(*collision_kinematics, collision_path, + pinocchio::COLLISION, *geometry); + for (const auto& object : geometry->geometryObjects) { + if (!object.geometry) { + throw std::runtime_error("Null collision geometry: " + object.name); + } + object.geometry->computeLocalAABB(); + } + collision_urdf_path_ = std::move(collision_path); + collision_kinematics_ = std::move(collision_kinematics); + collision_geometry_ = std::move(geometry); + return true; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][loadCollisionGeometry] path=" << collision_path << ": " << exception.what(); + return false; + } +} + +bool RobotModel::hasKinematics() const +{ + return static_cast(kinematics_); +} + +const pinocchio::Model& RobotModel::kinematics() const +{ + if (!kinematics_) { + throw std::logic_error("Robot kinematics are not loaded"); + } + return *kinematics_; +} + +bool RobotModel::hasCollisionGeometry() const +{ + return collisionGeometryCount() > 0; +} + +std::size_t RobotModel::collisionGeometryCount() const +{ + return collision_geometry_ ? collision_geometry_->ngeoms : 0; +} + +const std::string& RobotModel::urdfPath() const +{ + return urdf_path_; +} + +const std::string& RobotModel::collisionUrdfPath() const +{ + return collision_urdf_path_; +} + +std::vector RobotModel::collisionBodies( + const std::vector& joint_positions, + const std::vector& active_joint_names) const +{ + try { + if (!kinematics_) { + throw std::logic_error("Robot kinematics are not loaded"); + } + const auto& model = collision_kinematics_ ? *collision_kinematics_ : *kinematics_; + const auto& names = active_joint_names.empty() ? joint_names : active_joint_names; + if (joint_positions.size() != names.size()) { + throw std::invalid_argument("Joint position size mismatch: expected " + + std::to_string(names.size()) + ", got " + + std::to_string(joint_positions.size())); + } + std::unordered_set active_joint_ids; + Eigen::VectorXd q = pinocchio::neutral(model); + for (std::size_t index = 0; index < names.size(); ++index) { + const auto& joint_name = names[index]; + if (joint_name.empty() || !model.existJointName(joint_name)) { + throw std::invalid_argument("Joint not found in URDF: " + joint_name); + } + const auto joint_id = model.getJointId(joint_name); + if (!active_joint_ids.insert(joint_id).second) { + throw std::invalid_argument("Active joint names must be unique: " + joint_name); + } + const auto& joint = model.joints[joint_id]; + if (joint.nq() != 1 || joint.nv() != 1) { + throw std::invalid_argument("Only one-DoF active joints are supported: " + joint_name); + } + if (!std::isfinite(joint_positions[index])) { + throw std::invalid_argument("Non-finite joint position: " + joint_name); + } + q[joint.idx_q()] = joint_positions[index]; + } + if (!hasCollisionGeometry()) { + return {}; + } + + const auto& geometry = *collision_geometry_; + // Reuse one workspace per thread; switching models rebuilds it. Retain + // the immutable resources so reloads cannot reuse a stale model address. + thread_local std::shared_ptr cached_model; + thread_local std::shared_ptr cached_geometry; + thread_local std::unique_ptr data; + thread_local std::unique_ptr geometry_data; + if (cached_model != collision_kinematics_) { + data = std::make_unique(model); + cached_model = collision_kinematics_; + } + if (cached_geometry != collision_geometry_) { + geometry_data = std::make_unique(geometry); + cached_geometry = collision_geometry_; + } + pinocchio::updateGeometryPlacements( + model, *data, geometry, *geometry_data, q); + std::vector bodies; + bodies.reserve(geometry.ngeoms); + for (pinocchio::GeomIndex id = 0; id < geometry.ngeoms; ++id) { + const auto& object = geometry.geometryObjects[id]; + if (object.parentJoint != 0 && !active_joint_ids.count(object.parentJoint)) { + continue; + } + const auto& placement = geometry_data->oMg[id]; + if (!placement.translation().allFinite() || !placement.rotation().allFinite()) { + throw std::runtime_error("Non-finite collision body pose: " + object.name); + } + CollisionBody body; + body.geometry_index = id; + body.name = object.name; + body.link_name = object.parentFrame < model.frames.size() + ? model.frames[object.parentFrame].name : object.name; + if (object.parentJoint != 0) { + body.joint_name = model.names[object.parentJoint]; + const auto parent = model.parents[object.parentJoint]; + if (parent != 0) { + body.parent_joint_name = model.names[parent]; + } + } + body.geometry = object.geometry; + body.position = placement.translation(); + body.orientation = Eigen::Quaterniond(placement.rotation()).normalized(); + body.bounding_radius_m = std::max(0.0, body.geometry->aabb_radius); + bodies.push_back(std::move(body)); + } + return bodies; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][collisionBodies] " << exception.what(); + throw; + } +} + +bool RobotModel::fixedFramePose(const std::string& frame_name, Eigen::Isometry3d& pose) const +{ + if (!kinematics_) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] robot kinematics are not loaded"; + return false; + } + const auto& model = collision_kinematics_ ? *collision_kinematics_ : *kinematics_; + if (frame_name.empty() || !model.existFrame(frame_name)) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] frame not found in URDF: " << frame_name; + return false; + } + const auto& frame = model.frames[model.getFrameId(frame_name)]; + if (frame.parentJoint != 0) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] frame must be fixed to the model root: " << frame_name; + return false; + } + pose.matrix() = frame.placement.toHomogeneousMatrix(); + return true; +} + +bool RobotModel::containsName(const std::string& name) const +{ + const auto has_name = [&name](const pinocchio::Model& model) { + return model.existJointName(name) || model.existFrame(name); + }; + return (kinematics_ && has_name(*kinematics_)) || + (collision_geometry_ && + (has_name(*collision_kinematics_) || + collision_geometry_->existGeometryName(name))); +} + +} // namespace cmvr diff --git a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h index 99099e5f..7ec76dee 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h +++ b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h @@ -2,6 +2,7 @@ #define CMVR_ES_MUJOCO_WORLD_H #include +#include #include #include #include @@ -46,6 +47,12 @@ public: bool isLoaded() const; bool isRunning() const; double timestep() const; + // Pair one online control update with one physics step. The caller may + // read feedback and submit commands between begin/end without a world lock. + // finished=false submits this cycle; finished=true also unregisters the + // controller and must be called on every exit, even between cycles. + double beginControlCycle(const std::string& controller); + void endControlCycle(const std::string& controller, bool finished); const std::string& lastError() const; const std::string& modelPath() const; @@ -54,8 +61,9 @@ public: bool getJointPosition(const std::string& joint_name, double& position) const; bool getJointVelocity(const std::string& joint_name, double& velocity) const; - bool getJointStates(const std::vector& names, - std::vector& positions, std::vector& velocities) const; + bool getJointStates(const std::vector& joint_names, + std::vector& positions, + std::vector& velocities) const; bool setJointPosition(const std::string& joint_name, double position); bool setJointVelocity(const std::string& joint_name, double velocity); bool setJointTargetPosition(const std::string& joint_name, double position); @@ -68,7 +76,7 @@ public: const std::vector& positions, const std::vector& velocities); bool setJointTargetVelocity(const std::string& joint_name, double velocity); - bool setJointTargetVelocities(const std::vector& names, + bool setJointTargetVelocities(const std::vector& joint_names, const std::vector& velocities); mjModel* model(); @@ -114,6 +122,15 @@ private: void applyDirectControlLocked(double dt); mutable std::mutex mutex_; + struct ControlCycle { + bool granted{false}; + bool acquired{false}; + bool submitted{false}; + }; + std::mutex control_mutex_; + std::condition_variable control_cv_; + std::unordered_map control_cycles_; + bool control_window_open_{false}; Options options_; mjModel* model_{nullptr}; mjData* data_{nullptr}; diff --git a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp index 6527c19f..b5f1d873 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp +++ b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "common/base/logging/logger.h" @@ -167,11 +168,56 @@ bool MujocoWorld::start() void MujocoWorld::stop() { - stop_requested_.store(true); + { + std::lock_guard lock(control_mutex_); + stop_requested_.store(true); + } + control_cv_.notify_all(); if (simulation_thread_.joinable()) { simulation_thread_.join(); } running_.store(false); + std::lock_guard lock(control_mutex_); + control_cycles_.clear(); + control_window_open_ = false; +} + +double MujocoWorld::beginControlCycle(const std::string& controller) +{ + const double dt = timestep(); + std::unique_lock lock(control_mutex_); + if (!running_.load() || stop_requested_.load() || controller.empty()) { + throw std::runtime_error("MuJoCo control cycle is unavailable"); + } + auto inserted = control_cycles_.try_emplace(controller); + if (inserted.second && control_window_open_) inserted.first->second.granted = true; + const bool ready = control_cv_.wait_for(lock, std::chrono::seconds(1), [&] { + const auto it = control_cycles_.find(controller); + return stop_requested_.load() || !running_.load() || + (it != control_cycles_.end() && it->second.granted && !it->second.acquired); + }); + if (!ready || stop_requested_.load() || !running_.load()) { + control_cycles_.erase(controller); + control_cv_.notify_all(); + throw std::runtime_error("MuJoCo control cycle stopped or timed out"); + } + control_cycles_.at(controller).acquired = true; + return dt; +} + +void MujocoWorld::endControlCycle(const std::string& controller, const bool finished) +{ + std::lock_guard lock(control_mutex_); + const auto it = control_cycles_.find(controller); + if (it == control_cycles_.end()) return; + if (finished) { + control_cycles_.erase(it); + } else if (it->second.acquired) { + it->second.acquired = false; + it->second.granted = false; + it->second.submitted = true; + } + control_cv_.notify_all(); } void MujocoWorld::reset() @@ -277,18 +323,24 @@ bool MujocoWorld::setJointPosition(const std::string& joint_name, const double p return true; } -bool MujocoWorld::getJointStates(const std::vector& names, - std::vector& positions, std::vector& velocities) const +bool MujocoWorld::getJointStates(const std::vector& joint_names, + std::vector& positions, + std::vector& velocities) const { - if (names.empty() || &positions == &velocities) return false; + if (joint_names.empty() || &positions == &velocities) { + return false; + } std::lock_guard lock(mutex_); std::vector joints; - for (const auto& name : names) { + joints.reserve(joint_names.size()); + for (const auto& name : joint_names) { const JointHandle* joint = nullptr; if (!findJointLocked(name, joint) || std::find(joints.begin(), joints.end(), joint) != joints.end() || !std::isfinite(data_->qpos[joint->qpos_adr]) || - !std::isfinite(data_->qvel[joint->qvel_adr])) return false; + !std::isfinite(data_->qvel[joint->qvel_adr])) { + return false; + } joints.push_back(joint); } positions.resize(joints.size()); @@ -300,28 +352,6 @@ bool MujocoWorld::getJointStates(const std::vector& names, return true; } -bool MujocoWorld::setJointTargetVelocities(const std::vector& names, - const std::vector& velocities) -{ - if (names.empty() || names.size() != velocities.size()) return false; - std::lock_guard lock(mutex_); - std::vector joints; - for (std::size_t i = 0; i < names.size(); ++i) { - JointHandle* joint = nullptr; - if (!std::isfinite(velocities[i]) || !findJointLocked(names[i], joint) || - std::find(joints.begin(), joints.end(), joint) != joints.end()) return false; - joints.push_back(joint); - } - // Validate all entries before changing any command. - for (std::size_t i = 0; i < joints.size(); ++i) { - auto* joint = joints[i]; - if (joint->mode != TargetMode::DirectVelocity) joint->position_reference = data_->qpos[joint->qpos_adr]; - joint->target_velocity = velocities[i]; - joint->mode = TargetMode::DirectVelocity; - } - return true; -} - bool MujocoWorld::setJointVelocity(const std::string& joint_name, const double velocity) { std::lock_guard lock(mutex_); @@ -455,6 +485,35 @@ bool MujocoWorld::setJointTargetVelocity(const std::string& joint_name, const do return true; } +bool MujocoWorld::setJointTargetVelocities(const std::vector& joint_names, + const std::vector& velocities) +{ + if (joint_names.empty() || joint_names.size() != velocities.size()) { + return false; + } + std::lock_guard lock(mutex_); + std::vector joints; + joints.reserve(joint_names.size()); + for (std::size_t i = 0; i < joint_names.size(); ++i) { + JointHandle* joint = nullptr; + if (!std::isfinite(velocities[i]) || !findJointLocked(joint_names[i], joint) || + std::find(joints.begin(), joints.end(), joint) != joints.end()) { + return false; + } + joints.push_back(joint); + } + // Validate the entire batch before changing any target or control mode. + for (std::size_t i = 0; i < joints.size(); ++i) { + auto* joint = joints[i]; + if (joint->mode != TargetMode::DirectVelocity) { + joint->position_reference = data_->qpos[joint->qpos_adr]; + } + joint->target_velocity = velocities[i]; + joint->mode = TargetMode::DirectVelocity; + } + return true; +} + mjModel* MujocoWorld::model() { return model_; @@ -666,6 +725,22 @@ void MujocoWorld::simulationLoop() while (!stop_requested_.load()) { { + std::unique_lock control_lock(control_mutex_); + control_window_open_ = true; + for (auto& item : control_cycles_) { + item.second.granted = true; + item.second.submitted = false; + } + control_cv_.notify_all(); + control_cv_.wait(control_lock, [&] { + return stop_requested_.load() || std::all_of( + control_cycles_.begin(), control_cycles_.end(), + [](const auto& item) { return item.second.submitted; }); + }); + control_window_open_ = false; + if (stop_requested_.load()) break; + // Keep the cycle gate closed until this complete command has been + // consumed; the controller then observes the resulting feedback. std::lock_guard lock(mutex_); if (model_ == nullptr || data_ == nullptr) { break; @@ -685,6 +760,7 @@ void MujocoWorld::simulationLoop() running_.store(false); CMVR_LOG(INFO) << "[MujocoWorld] simulation stopped"; + control_cv_.notify_all(); } void MujocoWorld::applyControlLocked() diff --git a/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake b/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake new file mode 100644 index 00000000..1a6e87b8 --- /dev/null +++ b/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake @@ -0,0 +1,17 @@ +# CMVR package metadata for the bundled, header-only Eigen source layout. +get_filename_component(_cmvr_eigen_root "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE) +if(NOT EXISTS "${_cmvr_eigen_root}/Eigen/Core") + set(Eigen3_FOUND FALSE) + return() +endif() +if(NOT TARGET Eigen3::Eigen) + add_library(Eigen3::Eigen INTERFACE IMPORTED) + set_target_properties(Eigen3::Eigen PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${_cmvr_eigen_root}") +endif() +set(Eigen3_FOUND TRUE) +set(EIGEN3_FOUND TRUE) +set(EIGEN3_INCLUDE_DIR "${_cmvr_eigen_root}") +set(EIGEN3_INCLUDE_DIRS "${_cmvr_eigen_root}") +set(EIGEN3_VERSION_STRING "3.4.0") +unset(_cmvr_eigen_root) diff --git a/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake b/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake new file mode 100644 index 00000000..17600511 --- /dev/null +++ b/dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake @@ -0,0 +1,9 @@ +set(PACKAGE_VERSION "3.4.0") +set(PACKAGE_VERSION_COMPATIBLE FALSE) +set(PACKAGE_VERSION_EXACT FALSE) +if(PACKAGE_FIND_VERSION VERSION_LESS_EQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_COMPATIBLE TRUE) +endif() +if(PACKAGE_FIND_VERSION VERSION_EQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) +endif() diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h new file mode 100644 index 00000000..4979bceb --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h @@ -0,0 +1,233 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston */ + +#ifndef OMPL_BASE_CONSTRAINED_SPACE_INFORMATION_ +#define OMPL_BASE_CONSTRAINED_SPACE_INFORMATION_ + +#include + +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/spaces/constraint/ConstrainedStateSpace.h" +#include "ompl/base/spaces/constraint/AtlasChart.h" +#include "ompl/base/spaces/constraint/AtlasStateSpace.h" +#include "ompl/base/spaces/constraint/TangentBundleStateSpace.h" + +#include "ompl/util/ClassForward.h" +#include "ompl/util/Console.h" +#include "ompl/util/Exception.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ConstrainedSpaceInformation */ + OMPL_CLASS_FORWARD(ConstrainedSpaceInformation); + /// @endcond + + /** \brief Valid state sampler for constrained state spaces. */ + class ConstrainedValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor. Create a valid state sampler for a + * constrained state space. */ + ConstrainedValidStateSampler(const SpaceInformation *si) + : ValidStateSampler(si) + , sampler_(si->getStateSpace()->allocStateSampler()) + , constraint_(si->getStateSpace()->as()->getConstraint()) + { + } + + bool sample(State *state) override + { + // Rejection sample for at most attempts_ tries. + unsigned int tries = 0; + bool valid; + + do + sampler_->sampleUniform(state); + while (!(valid = si_->isValid(state) && constraint_->isSatisfied(state)) && ++tries < attempts_); + + return valid; + } + + bool sampleNear(State *state, const State *near, double distance) override + { + // Rejection sample for at most attempts_ tries. + unsigned int tries = 0; + bool valid; + do + sampler_->sampleUniformNear(state, near, distance); + while (!(valid = si_->isValid(state) && constraint_->isSatisfied(state)) && ++tries < attempts_); + + return valid; + } + + private: + /** \brief Underlying constrained state sampler. */ + StateSamplerPtr sampler_; + + /** \brief Constraint function. */ + const ConstraintPtr constraint_; + }; + + /** \brief Space information for a constrained state space. Implements + * more direct for getting motion states. */ + class ConstrainedSpaceInformation : public SpaceInformation + { + public: + /** \brief Constructor. Sets the instance of the state space to plan with. */ + ConstrainedSpaceInformation(StateSpacePtr space) : SpaceInformation(std::move(space)) + { + stateSpace_->as()->setSpaceInformation(this); + setValidStateSamplerAllocator([](const SpaceInformation *si) -> std::shared_ptr + { return std::make_shared(si); }); + } + + /** \brief Get \e count states that make up a motion between \e s1 + and \e s2. Returns the number of states that were added to \e + states. Uses the constrained state space's manifold traversal + method to obtain states. Will always allocate states. + + Otherwise, fewer states can be returned. + \param s1 the start state of the considered motion + \param s2 the end state of the considered motion + \param states the computed set of states along the specified motion + \param count is currently ignored + \param endpoints flag indicating whether \e s1 and \e s2 are to be included in states + \param alloc is currently ignored */ + unsigned int getMotionStates(const State *s1, const State *s2, std::vector &states, + unsigned int /*count*/, bool endpoints, bool /*alloc*/) const override + { + bool success = stateSpace_->as()->discreteGeodesic(s1, s2, true, &states); + + if (endpoints) + { + if (!success && states.empty()) + states.push_back(cloneState(s1)); + + if (success) + states.push_back(cloneState(s2)); + } + + return states.size(); + } + }; + + /** \brief Space information for a tangent bundle-based state space. + * Implements more direct for getting motion states and checking motion, + * as the lazy approach requires post-processing. */ + class TangentBundleSpaceInformation : public ConstrainedSpaceInformation + { + public: + /** \brief Constructor. Sets the instance of the state space to plan with. */ + TangentBundleSpaceInformation(StateSpacePtr space) : ConstrainedSpaceInformation(std::move(space)) + { + } + + /** \brief Get \e count states that make up a motion between \e s1 + and \e s2. Returns the number of states that were added to \e + states. Uses the constrained state space's manifold traversal + method to obtain states. Will always allocate states. As tangent + bundle is lazy, the states are projected onto the manifold so + that they satisfy constraints. + + Otherwise, fewer states can be returned. + \param s1 the start state of the considered motion + \param s2 the end state of the considered motion + \param states the computed set of states along the specified motion + \param count is currently ignored + \param endpoints flag indicating whether \e s1 and \e s2 are to be included in states + \param alloc is currently ignored + */ + unsigned int getMotionStates(const State *s1, const State *s2, std::vector &states, + unsigned int /*count*/, bool /*endpoints*/, bool /*alloc*/) const override + { + auto &&atlas = stateSpace_->as(); + + std::vector temp; + bool success = atlas->discreteGeodesic(s1, s2, true, &temp); + + if (!success && temp.empty()) + temp.push_back(cloneState(s1)); + + auto it = temp.begin(); + for (; it != temp.end(); ++it) + { + auto astate = (*it)->as(); + if (!atlas->project(astate)) + break; + + states.push_back(astate); + } + + while (it != temp.end()) + freeState(*it++); + + return states.size(); + } + + /** \brief Incrementally check if the path between two motions is + valid. Also compute the last state that was valid and the time + of that state. The time is used to parametrize the motion from + s1 to s2, s1 being at t = 0 and s2 being at t = 1. This function + assumes s1 is valid. As tangent bundle is lazy, the last valid + state is projected onto the manifold. + + \param s1 start state of the motion to be checked (assumed to be valid) + \param s2 final state of the motion to be checked + \param lastValid first: storage for the last valid state (may be nullptr); this need not be different + from \e s1 or \e s2. second: the time (between 0 and 1) of the last valid state, on the motion from \e + s1 to \e s2 */ + bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const override + { + auto &&atlas = stateSpace_->as(); + bool valid = motionValidator_->checkMotion(s1, s2, lastValid); + + if (lastValid.first != nullptr) + { + auto astate = lastValid.first->as(); + if (!atlas->project(astate)) + valid = false; + } + + return valid; + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h new file mode 100644 index 00000000..1990f5c3 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h @@ -0,0 +1,325 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston, Ryan Luna */ + +#ifndef OMPL_BASE_CONSTRAINTS_CONSTRAINT_ +#define OMPL_BASE_CONSTRAINTS_CONSTRAINT_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/OptimizationObjective.h" +#include "ompl/util/ClassForward.h" +#include "ompl/util/Exception.h" + +#include +#include +#include + +namespace ompl +{ + namespace magic + { + /** \brief Default projection tolerance of a constraint unless otherwise + * specified. */ + static const double CONSTRAINT_PROJECTION_TOLERANCE = 1e-4; + + /** \brief Maximum number of iterations in projection routine until + * giving up. */ + static const unsigned int CONSTRAINT_PROJECTION_MAX_ITERATIONS = 50; + } // namespace magic + + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::Constraint */ + OMPL_CLASS_FORWARD(Constraint); + /// @endcond + + /** \class ompl::base::ConstraintPtr + \brief A shared pointer wrapper for ompl::base::Constraint */ + + /** \brief Definition of a differentiable holonomic constraint on a + * configuration space. See \ref constrainedPlanning for more details. + */ + class Constraint + { + public: + /** \brief Constructor. The dimension of the ambient configuration + space as well as the dimension of the function's output need to be + specified (the co-dimension of the constraint manifold). I.E., for + a sphere constraint function in \f$\mathbb{R}^3$, + \f[ + F(q) = \left\lVert q \right\rVert - 1 \qquad F(q) : \f\mathbb{R}^3 \rightarrow \mathbb{R} + \f] + \a ambientDim will be 3, and \a coDim will be 1. + */ + Constraint(const unsigned int ambientDim, const unsigned int coDim, + double tolerance = magic::CONSTRAINT_PROJECTION_TOLERANCE) + : n_(ambientDim) + , k_(ambientDim - coDim) + , tolerance_(tolerance) + , maxIterations_(magic::CONSTRAINT_PROJECTION_MAX_ITERATIONS) + { + if (n_ <= 0 || k_ <= 0) + throw ompl::Exception("ompl::base::Constraint(): " + "Ambient and manifold dimensions must be positive."); + } + + virtual ~Constraint() = default; + + /** @name Constraint Function Operations + @{ */ + + /** \brief Compute the constraint function at \a state. Result is + returned in \a out, which should be allocated to size \a coDim. */ + virtual void function(const State *state, Eigen::Ref out) const; + + /** \brief Compute the constraint function at \a x. Result is + returned in \a out, which should be allocated to size \a coDim. */ + virtual void function(const Eigen::Ref &x, + Eigen::Ref out) const = 0; + + /** \brief Compute the Jacobian of the constraint function at \a + state. Result is returned in \a out, which should be allocated to + size \a coDim by \a ambientDim. Default implementation performs the + differentiation numerically with a seven-point central difference + stencil. It is best to provide an analytic formulation. */ + virtual void jacobian(const State *state, Eigen::Ref out) const; + + /** \brief Compute the Jacobian of the constraint function at \a x. + Result is returned in \a out, which should be allocated to size \a + coDim by \a ambientDim. Default implementation performs the + differentiation numerically with a seven-point central difference + stencil. It is best to provide an analytic formulation. */ + virtual void jacobian(const Eigen::Ref &x, Eigen::Ref out) const; + + /** @} */ + + /** @name Other Function Operations + @{ */ + + /** \brief Project a state \a state given the constraints. If a + valid projection cannot be found, this method will return false. + Even if this method fails, \a state will be modified. */ + virtual bool project(State *state) const; + + /** \brief Project a state \a x given the constraints. If a valid + projection cannot be found, this method will return false. */ + virtual bool project(Eigen::Ref x) const; + + /** \brief Returns the distance of \a state to the constraint + * manifold. */ + virtual double distance(const State *state) const; + + /** \brief Returns the distance of \a x to the constraint manifold. */ + virtual double distance(const Eigen::Ref &x) const; + + /** \brief Check whether a state \a state satisfies the + * constraints */ + virtual bool isSatisfied(const State *state) const; + + /** \brief Check whether a state \a x satisfies the constraints */ + virtual bool isSatisfied(const Eigen::Ref &x) const; + + /** @} */ + + /** @name Getters and Setters + @{ */ + + /** \brief Returns the dimension of the ambient space. */ + unsigned int getAmbientDimension() const + { + return n_; + } + + /** \brief Returns the dimension of the manifold. */ + unsigned int getManifoldDimension() const + { + return k_; + } + + /** \brief Returns the dimension of the manifold. */ + unsigned int getCoDimension() const + { + return n_ - k_; + } + + /** \brief Sets the underlying manifold dimension. */ + void setManifoldDimension(unsigned int k) + { + if (k <= 0) + throw ompl::Exception("ompl::base::Constraint(): " + "Space is over constrained!"); + k_ = k; + } + + /** \brief Returns the tolerance of the projection routine. */ + double getTolerance() const + { + return tolerance_; + } + + /** \brief Returns the maximum number of allowed iterations in the + * projection routine. */ + unsigned int getMaxIterations() const + { + return maxIterations_; + } + + /** \brief Sets the projection tolerance. */ + void setTolerance(const double tolerance) + { + if (tolerance <= 0) + throw ompl::Exception("ompl::base::Constraint::setProjectionTolerance(): " + "tolerance must be positive."); + tolerance_ = tolerance; + } + + /** \brief Sets the maximum number of iterations in the projection + * routine. */ + void setMaxIterations(const unsigned int iterations) + { + if (iterations == 0) + throw ompl::Exception("ompl::base::Constraint::setProjectionMaxIterations(): " + "iterations must be positive."); + maxIterations_ = iterations; + } + + /** @} */ + + protected: + /** \brief Ambient space dimension. */ + const unsigned int n_; + + /** \brief Manifold dimension. */ + unsigned int k_; + + /** \brief Tolerance for Newton method used in projection onto + * manifold. */ + double tolerance_; + + /** \brief Maximum number of iterations for Newton method used in + * projection onto manifold. */ + unsigned int maxIterations_; + }; + + /// @cond IGNORE + OMPL_CLASS_FORWARD(ConstraintIntersection); + /// @endcond + + /** \brief Definition of a constraint composed of multiple constraints + that all must be satisfied simultaneously. This class `stacks' the + constraint functions together. */ + class ConstraintIntersection : public Constraint + { + public: + /** \brief Constructor. If constraints is empty assume it will be + * filled later. */ + ConstraintIntersection(const unsigned int ambientDim, std::vector constraints) + : Constraint(ambientDim, 0) + { + for (const auto &constraint : constraints) + addConstraint(constraint); + } + + /** \brief Constructor. If constraints is empty assume it will be + * filled later. */ + ConstraintIntersection(const unsigned int ambientDim, std::initializer_list constraints) + : Constraint(ambientDim, 0) + { + for (const auto &constraint : constraints) + addConstraint(constraint); + } + + void function(const Eigen::Ref &x, Eigen::Ref out) const override + { + unsigned int i = 0; + for (const auto &constraint : constraints_) + { + constraint->function(x, out.segment(i, constraint->getCoDimension())); + i += constraint->getCoDimension(); + } + } + + void jacobian(const Eigen::Ref &x, Eigen::Ref out) const override + { + unsigned int i = 0; + for (const auto &constraint : constraints_) + { + constraint->jacobian(x, out.block(i, 0, constraint->getCoDimension(), n_)); + i += constraint->getCoDimension(); + } + } + + protected: + void addConstraint(const ConstraintPtr &constraint) + { + setManifoldDimension(k_ - constraint->getCoDimension()); + constraints_.push_back(constraint); + } + + /** \brief Constituent constraints. */ + std::vector constraints_; + }; + + /// @cond IGNORE + OMPL_CLASS_FORWARD(ConstraintObjective); + /// @endcond + + /** \brief Wrapper around ompl::base::Constraint to use as an + * optimization objective. */ + class ConstraintObjective : public OptimizationObjective + { + public: + /** \brief Constructor. */ + ConstraintObjective(ConstraintPtr constraint, SpaceInformationPtr si) + : OptimizationObjective(std::move(si)), constraint_(std::move(constraint)) + { + } + + /** \brief Evaluate a cost map defined on the state space at a state + * \e s. Cost map is defined as the distance from the constraint. */ + Cost stateCost(const State *s) const override + { + return Cost(constraint_->distance(s)); + } + + protected: + /** \brief Optimizing constraint */ + ConstraintPtr constraint_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h new file mode 100644 index 00000000..3c889c13 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h @@ -0,0 +1,70 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres, Ioan Sucan */ + +#ifndef OMPL_BASE_COST_ +#define OMPL_BASE_COST_ + +#include + +namespace ompl +{ + namespace base + { + /** \brief Definition of a cost value. Can represent the cost of a motion or the cost of a state. */ + class Cost + { + public: + /** \brief Construct cost with a specified value */ + explicit Cost(double v = 0.0) : v_(v) + { + } + + /** \brief The value of the cost */ + double value() const + { + return v_; + } + + private: + /** \brief The value of the cost */ + double v_; + }; + + /** \brief Output operator for Cost */ + std::ostream &operator<<(std::ostream &stream, Cost c); + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h new file mode 100644 index 00000000..ba9316ff --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h @@ -0,0 +1,78 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_DISCRETE_MOTION_VALIDATOR_ +#define OMPL_BASE_DISCRETE_MOTION_VALIDATOR_ + +#include "ompl/base/MotionValidator.h" +#include "ompl/base/SpaceInformation.h" + +namespace ompl +{ + namespace base + { + /** \brief A motion validator that only uses the state validity checker. Motions are checked for validity at a + * specified resolution. */ + class DiscreteMotionValidator : public MotionValidator + { + public: + /** \brief Constructor */ + DiscreteMotionValidator(SpaceInformation *si) : MotionValidator(si) + { + defaultSettings(); + } + + /** \brief Constructor */ + DiscreteMotionValidator(const SpaceInformationPtr &si) : MotionValidator(si) + { + defaultSettings(); + } + + ~DiscreteMotionValidator() override = default; + + bool checkMotion(const State *s1, const State *s2) const override; + + bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const override; + + private: + StateSpace *stateSpace_; + + void defaultSettings(); + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h new file mode 100644 index 00000000..22f293e1 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h @@ -0,0 +1,316 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Willow Garage + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GENERIC_PARAM_ +#define OMPL_BASE_GENERIC_PARAM_ + +#include "ompl/util/Console.h" +#include "ompl/util/String.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::GenericParam */ + OMPL_CLASS_FORWARD(GenericParam); + /// @endcond + + /** \brief Motion planning algorithms often employ parameters + to guide their exploration process. (e.g., goal + biasing). Motion planners (and some of their components) + use this class to declare what the parameters are, in a + generic way, so that they can be set externally. */ + class GenericParam + { + public: + /** \brief The constructor of a parameter takes the name of the parameter (\e name) */ + GenericParam(std::string name) : name_(std::move(name)) + { + } + + virtual ~GenericParam() = default; + + /** \brief Get the name of the parameter */ + const std::string &getName() const + { + return name_; + } + + /** \brief Set the name of the parameter */ + void setName(const std::string &name) + { + name_ = name; + } + + /** \brief Set the value of the parameter. The value is taken in as a string, but converted to the type of + * that parameter. */ + virtual bool setValue(const std::string &value) = 0; + + /** \brief Retrieve the value of the parameter, as a string. */ + virtual std::string getValue() const = 0; + + /** \brief Assignment operator by type. This is just for convenience, as it just calls setValue() */ + template + GenericParam &operator=(const T &value) + { + setValue(std::to_string(value)); + return *this; + } + + /** \brief Set a suggested range */ + void setRangeSuggestion(const std::string &rangeSuggestion) + { + rangeSuggestion_ = rangeSuggestion; + } + + /** \brief Get the suggested range of values */ + const std::string &getRangeSuggestion() const + { + return rangeSuggestion_; + } + + protected: + /** \brief The name of the parameter */ + std::string name_; + + /** \brief Suggested range for the parameter + + This can be used to provide a hint to, e.g., a GUI. The + convention used in OMPL is to denote ranges for the + following types as follows: + - \c bool: "0,1" + - \c enum: ",,,..." + - \c int, \c double: either "first:last" or "first:stepsize:last". + In the first case, the stepsize is assumed to be 1. It is + important to use floating point representations for double + ranges (i.e., "1." instead of "1") to make sure the type is + deduced correctly. + */ + std::string rangeSuggestion_; + }; + + /** \brief This is a helper class that instantiates parameters with different data types. */ + template + class SpecificParam : public GenericParam + { + public: + /** \brief The type for the 'setter' function for this parameter */ + using SetterFn = std::function; + + /** \brief The type for the 'getter' function for this parameter */ + using GetterFn = std::function; + + /** \brief An explicit instantiation of a parameter \e name requires the \e setter function and optionally + the \e + getter function. */ + SpecificParam(const std::string &name, SetterFn setter, GetterFn getter = GetterFn()) + : GenericParam(name), setter_(std::move(setter)), getter_(std::move(getter)) + { + if (!setter_ && !getter_) + OMPL_ERROR("At least one setter or getter function must be specified for parameter"); + } + + ~SpecificParam() override = default; + + bool setValue(const std::string &value) override + { + bool result = true; + try + { + if (setter_) + setter_(lexical_cast(value)); + } + catch (std::invalid_argument &e) + { + result = false; + OMPL_WARN("Invalid value format specified for parameter '%s': %s", name_.c_str(), e.what()); + } + + if (getter_) + OMPL_DEBUG("The value of parameter '%s' is now: '%s'", name_.c_str(), getValue().c_str()); + else + OMPL_DEBUG("The value of parameter '%s' was set to: '%s'", name_.c_str(), value.c_str()); + return result; + } + + std::string getValue() const override + { + return getter_ ? std::to_string(getter_()) : ""; + } + + protected: + /** \brief Helper function to convert strings into objects of type T + * + * Supported types are: bool, int, long, long long, unsigned int, unsigned long, unsigned long long, float, + * double, long double, char, std::string. + */ + T lexical_cast(const std::string &value) const; + + /** \brief The setter function for this parameter */ + SetterFn setter_; + + /** \brief The getter function for this parameter */ + GetterFn getter_; + }; + + template <> + inline std::string ompl::base::SpecificParam::getValue() const + { + return getter_ ? ompl::toString(getter_()) : ""; + } + template <> + inline std::string ompl::base::SpecificParam::getValue() const + { + return getter_ ? ompl::toString(getter_()) : ""; + } + template <> + inline std::string ompl::base::SpecificParam::getValue() const + { + return getter_ ? ompl::toString(getter_()) : ""; + } + template <> + inline std::string ompl::base::SpecificParam::getValue() const + { + return getter_ ? getter_() : ""; + } + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ParamSet */ + OMPL_CLASS_FORWARD(ParamSet); + /// @endcond + + /** \brief Maintain a set of parameters */ + class ParamSet + { + public: + /** \brief This function declares a parameter \e name, and specifies the \e setter and \e getter functions. + */ + template + void declareParam( + const std::string &name, const typename SpecificParam::SetterFn &setter, + const typename SpecificParam::GetterFn &getter = [] { return T(); }) + { + params_[name] = std::make_shared>(name, setter, getter); + } + + /** \brief Add a parameter to the set */ + void add(const GenericParamPtr ¶m); + + /** \brief Remove a parameter from the set */ + void remove(const std::string &name); + + /** \brief Include the params of a different ParamSet into this one. Optionally include a prefix for each of + * the parameters */ + void include(const ParamSet &other, const std::string &prefix = ""); + + /** \brief Algorithms in OMPL often have parameters that + can be set externally. While each algorithm will have + their own getter and setter functions specifically for + those parameters, this function allows setting + parameters generically, for any algorithm that + declares parameters, by specifying the parameter name + \e key and its value \e value (both as string, but \e + value is cast to the type desired by the corresponding + setter). Under the hood, this calls SpecificParam::setValue(). + This ability makes it easy to automatically configure + using external sources (e.g., a configuration + file). The function returns true if the parameter was + parsed and set successfully and false otherwise. */ + bool setParam(const std::string &key, const std::string &value); + + /** \brief Get the value of the parameter named \e key. Store the value as string in \e value and return + * true if the parameter was found. Return false otherwise. */ + bool getParam(const std::string &key, std::string &value) const; + + /** \brief Set the values for a set of parameters. The parameter names are the keys in the map \e kv. + The corresponding key values in \e kv are set as the parameter values. + Return true if all parameters were set successfully. This function simply calls setParam() multiple + times. + If \e ignoreUnknown is true, then no attempt is made to set unknown + parameters (and thus no errors are reported) */ + bool setParams(const std::map &kv, bool ignoreUnknown = false); + + /** \brief Get the known parameter as a map from names to their values cast as string */ + void getParams(std::map ¶ms) const; + + /** \brief List the names of the known parameters */ + void getParamNames(std::vector ¶ms) const; + + /** \brief List the values of the known parameters, in the same order as getParamNames() */ + void getParamValues(std::vector &vals) const; + + /** \brief Get the map from parameter names to parameter descriptions */ + const std::map &getParams() const; + + /** \brief Get the parameter that corresponds to a specified name. An empty shared ptr is returned if the + * parameter does not exist */ + const GenericParamPtr &getParam(const std::string &key) const; + + /** \brief Check whether this set of parameters includes the parameter named \e key */ + bool hasParam(const std::string &key) const; + + /** \brief Access operator for parameters, by name. If the parameter is not defined, an exception is thrown + */ + GenericParam &operator[](const std::string &key); + + /** \brief Get the number of parameters maintained by this instance */ + std::size_t size() const + { + return params_.size(); + } + + /** \brief Clear all the set parameters */ + void clear(); + + /** \brief Print the parameters to a stream */ + void print(std::ostream &out) const; + + private: + std::map params_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h new file mode 100644 index 00000000..d84e821f --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h @@ -0,0 +1,154 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOAL_ +#define OMPL_BASE_GOAL_ + +#include "ompl/base/State.h" +#include "ompl/base/SpaceInformation.h" +#include "ompl/util/ClassForward.h" +#include "ompl/base/GoalTypes.h" +#include "ompl/util/Console.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::Goal */ + OMPL_CLASS_FORWARD(Goal); + /// @endcond + + /** \class ompl::base::GoalPtr + \brief A shared pointer wrapper for ompl::base::Goal */ + + /** \brief Abstract definition of goals.*/ + class Goal + { + public: + // non-copyable + Goal(const Goal &) = delete; + Goal &operator=(const Goal &) = delete; + + /** \brief Constructor. The goal must always know the space information it is part of */ + Goal(SpaceInformationPtr si); + + /** \brief Destructor.*/ + virtual ~Goal() = default; + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are casting to is indeed a goal */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are casting to is indeed a goal */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Return the goal type */ + GoalType getType() const + { + return type_; + } + + /** \brief Check if this goal can be cast to a particular goal type */ + bool hasType(GoalType type) const + { + return (type_ & type) == type; + } + + /** \brief Get the space information this goal is for */ + const SpaceInformationPtr &getSpaceInformation() const + { + return si_; + } + + /** \brief Return true if the state satisfies the goal + * constraints. */ + virtual bool isSatisfied(const State *st) const = 0; + + /** \brief Return true if the state satisfies the goal + * constraints and compute the distance between the state + * given as argument and the goal (even if the goal is + * not satisfied). This distance can be an + * approximation. It can even be set to a constant, if + * such a computation is not possible. + * \param st the state to check for validity + * \param distance location at which distance to goal will be stored + * \note The default implementation sets the distance to a constant. + * \note If this function returns true, + * isStartGoalPairValid() need not be called. */ + virtual bool isSatisfied(const State *st, double *distance) const; + + /** \brief Since there can be multiple starting states + (and multiple goal states) it is possible certain + pairs are not to be allowed. By default we however + assume all such pairs are allowed. Note: if this + function returns true, isSatisfied() need not be + called. */ + virtual bool isStartGoalPairValid(const State * /* start */, const State * /* goal */) const + { + return true; + } + + /** \brief Print information about the goal */ + virtual void print(std::ostream &out = std::cout) const; + + protected: + /** \brief Goal type */ + GoalType type_; + + /** \brief The space information for this goal */ + SpaceInformationPtr si_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h new file mode 100644 index 00000000..43d13bd4 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h @@ -0,0 +1,70 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOAL_TYPES_ +#define OMPL_BASE_GOAL_TYPES_ + +namespace ompl +{ + namespace base + { + /** \brief The type of goal */ + enum GoalType + { + /** \brief This bit is set if casting to generic goal regions (ompl::base::Goal) is possible. This bit shold + always be set */ + GOAL_ANY = 1, + + /** \brief This bit is set if casting to goal regions (ompl::base::GoalRegion) is possible */ + GOAL_REGION = GOAL_ANY + 2, + + /** \brief This bit is set if casting to sampleable goal regions (ompl::base::GoalSampleableRegion) is + possible */ + GOAL_SAMPLEABLE_REGION = GOAL_REGION + 4, + + /** \brief This bit is set if casting to goal state (ompl::base::GoalState) is possible */ + GOAL_STATE = GOAL_SAMPLEABLE_REGION + 8, + + /** \brief This bit is set if casting to goal states (ompl::base::GoalStates) is possible */ + GOAL_STATES = GOAL_SAMPLEABLE_REGION + 16, + + /** \brief This bit is set if casting to goal states (ompl::base::GoalLazySamples) is possible */ + GOAL_LAZY_SAMPLES = GOAL_STATES + 32 + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h new file mode 100644 index 00000000..7f2c17d2 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h @@ -0,0 +1,144 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_MOTION_VALIDATOR_ +#define OMPL_BASE_MOTION_VALIDATOR_ + +#include "ompl/base/State.h" +#include "ompl/util/ClassForward.h" +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::MotionValidator */ + OMPL_CLASS_FORWARD(MotionValidator); + /// @endcond + + /** \class ompl::base::MotionValidatorPtr + \brief A shared pointer wrapper for ompl::base::MotionValidator */ + + /** \brief Abstract definition for a class checking the + validity of motions -- path segments between states. This + is often called a local planner. The implementation of + this class must be thread safe. */ + class MotionValidator + { + public: + /** \brief Constructor */ + MotionValidator(SpaceInformation *si) : si_(si), valid_(0), invalid_(0) + { + } + + /** \brief Constructor */ + MotionValidator(const SpaceInformationPtr &si) : si_(si.get()), valid_(0), invalid_(0) + { + } + + virtual ~MotionValidator() = default; + + /** \brief Check if the path between two states (from \e s1 to \e s2) is valid. This function assumes \e s1 + is valid. + + \note This function updates the number of valid and invalid segments. */ + virtual bool checkMotion(const State *s1, const State *s2) const = 0; + + /** \brief Check if the path between two states is valid. Also compute the last state that was + valid and the time of that state. The time is used to parametrize the motion from \e s1 to \e s2, \e s1 + being at t = + 0 and \e s2 being at t = 1. This function assumes \e s1 is valid. + \param s1 start state of the motion to be checked (assumed to be valid) + \param s2 final state of the motion to be checked + \param lastValid first: storage for the last valid state (may be nullptr, if the user does not care + about the exact state); this need not be different from \e s1 or \e s2. second: the time (between 0 and + 1) of the last valid state, on the motion from \e s1 to \e s2. If the function returns false, \e + lastValid.first must be set to a valid state, even if that implies copying \e s1 to \e lastValid.first + (in case \e lastValid.second = 0). If the function returns true, \e lastValid.first and \e + lastValid.second should \b not be modified. + + \note This function updates the number of valid and invalid segments. */ + virtual bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const = 0; + + /** \brief Get the number of segments that tested as valid */ + unsigned int getValidMotionCount() const + { + return valid_; + } + + /** \brief Get the number of segments that tested as invalid */ + unsigned int getInvalidMotionCount() const + { + return invalid_; + } + + /** \brief Get the total number of segments tested, regardless of result */ + unsigned int getCheckedMotionCount() const + { + return valid_ + invalid_; + } + + /** \brief Get the fraction of segments that tested as valid */ + double getValidMotionFraction() const + { + return valid_ == 0 ? 0.0 : (double)valid_ / (double)(invalid_ + valid_); + } + + /** \brief Reset the counters for valid and invalid segments */ + void resetMotionCounter() + { + valid_ = invalid_ = 0; + } + + protected: + /** \brief The instance of space information this state validity checker operates on */ + SpaceInformation *si_; + + /** \brief Number of valid segments */ + mutable unsigned int valid_; + + /** \brief Number of invalid segments */ + mutable unsigned int invalid_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h new file mode 100644 index 00000000..647fee92 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h @@ -0,0 +1,306 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres, Ioan Sucan, Jonathan Gammell */ + +#ifndef OMPL_BASE_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OPTIMIZATION_OBJECTIVE_ + +#include "ompl/base/Cost.h" +#include "ompl/base/SpaceInformation.h" +#include "ompl/util/ClassForward.h" +#include "ompl/base/ProblemDefinition.h" +#include "ompl/base/samplers/InformedStateSampler.h" +#include "ompl/control/Control.h" + +#include +#include + +namespace ompl +{ + namespace base + { + class Goal; + + /** \brief The definition of a function which returns an admissible estimate of the optimal path cost from a + * given state to a goal. */ + using CostToGoHeuristic = std::function; + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::OptimizationObjective */ + OMPL_CLASS_FORWARD(OptimizationObjective); + /// @endcond + + /** \class ompl::base::OptimizationObjectivePtr + \brief A shared pointer wrapper for ompl::base::OptimizationObjective */ + + /** \brief Abstract definition of optimization objectives. + + \note This implementation has greatly benefited from discussions with Kris Hauser */ + class OptimizationObjective + { + public: + // non-copyable + OptimizationObjective(const OptimizationObjective &) = delete; + OptimizationObjective &operator=(const OptimizationObjective &) = delete; + + /** \brief Constructor. The objective must always know the space information it is part of. The cost + * threshold for objective satisfaction defaults to 0.0. */ + OptimizationObjective(SpaceInformationPtr si); + + virtual ~OptimizationObjective() = default; + + /** \brief Get the description of this optimization objective */ + const std::string &getDescription() const; + + /** \brief Check if the the given cost \e c satisfies the specified cost objective, defined as \e better \e + * than the specified threshold. */ + virtual bool isSatisfied(Cost c) const; + + /** \brief Returns the cost threshold currently being checked for objective satisfaction */ + Cost getCostThreshold() const; + + /** \brief Set the cost threshold for objective satisfaction. When a path is found with a cost better than + * the cost threshold, the objective is considered satisfied. */ + void setCostThreshold(Cost c); + + /** \brief Check whether the the cost \e c1 is considered better than the cost \e c2. By default, this + * returns true if if c1 is less than c2. */ + virtual bool isCostBetterThan(Cost c1, Cost c2) const; + + /** \brief Compare whether cost \e c1 and cost \e c2 are equivalent. By default defined as + * !isCostBetterThan(c1, c2) && !isCostBetterThan(c2, c1), as if c1 is not better than c2, and c2 is not + * better than c1, then they are equal. */ + virtual bool isCostEquivalentTo(Cost c1, Cost c2) const; + + /** \brief Returns whether the cost is finite or not. */ + virtual bool isFinite(Cost cost) const; + + /** \brief Return the minimum cost given \e c1 and \e c2. Uses isCostBetterThan. */ + virtual Cost betterCost(Cost c1, Cost c2) const; + + /** \brief Evaluate a cost map defined on the state space at a state \e s. */ + virtual Cost stateCost(const State *s) const = 0; + + /** \brief Get the cost that corresponds to the motion segment between \e s1 and \e s2 */ + virtual Cost motionCost(const State *s1, const State *s2) const = 0; + + /** \brief Get the cost that corresponds to the motion created by a control \e c applied for duration \e + * steps. The default implementation uses the identityCost. */ + virtual Cost controlCost(const control::Control *c, unsigned int steps) const; + + /** \brief Get the cost of the motion that starts at state \e s1, applies control \e c for \e steps + * propagation steps, and arrives at state \e s2. + * The default implementation combines the costs of motionCost(s1, s2) and controlCost(c, steps). + * Control planners should prefer this method over calling motionCost() and controlCost() separately.*/ + virtual Cost controlMotionCost(const State *s1, const control::Control *c, unsigned int steps, + const State *s2) const; + + /** \brief Get the cost that corresponds to combining the costs \e c1 and \e c2. Default implementation + * defines this combination as an addition. */ + virtual Cost combineCosts(Cost c1, Cost c2) const; + + /** \brief Get the cost that corresponds to subtracting the cost \e c2 from \e c1. */ + virtual Cost subtractCosts(Cost c1, Cost c2) const; + + /** \brief Get the identity cost value. The identity cost value is the cost c_i such that, for all costs c, + * combineCosts(c, c_i) = combineCosts(c_i, c) = c. In other words, combining a cost with the identity cost + * does not change the original cost. By default, a cost with the value 0.0 is returned. It's very important + * to override this with the proper identity value for your optimization objectives, or else optimal + * planners may not work. */ + virtual Cost identityCost() const; + + /** \brief Get a cost which is greater than all other costs in this OptimizationObjective; required for use + * in Dijkstra/Astar. Defaults to returning the double value inf.*/ + virtual Cost infiniteCost() const; + + /** \brief Returns a cost value corresponding to starting at a state \e s. No optimal planners currently + * support this method. Defaults to returning the objective's identity cost. */ + virtual Cost initialCost(const State *s) const; + + /** \brief Returns a cost value corresponding to a path ending at a state \e s. No optimal planners + * currently support this method. Defaults to returning the objective's identity cost. */ + virtual Cost terminalCost(const State *s) const; + + /** \brief Check if this objective has a symmetric cost metric, i.e. motionCost(s1, s2) = motionCost(s2, + * s1). Default implementation returns whether the underlying state space has symmetric interpolation. */ + virtual bool isSymmetric() const; + + /** \brief Compute the average state cost of this objective by taking a sample of \e numStates states */ + virtual Cost averageStateCost(unsigned int numStates) const; + + /** \brief Set the cost-to-go heuristic function for this objective. The cost-to-go heuristic is a function + * which returns an admissible estimate of the optimal path cost from a given state to a goal, where + * "admissible" means that the estimated cost is always less than the true optimal cost. */ + void setCostToGoHeuristic(const CostToGoHeuristic &costToGo); + + /** \brief Check if this objective has a cost-to-go heuristic function. */ + bool hasCostToGoHeuristic() const; + + /** \brief Uses a cost-to-go heuristic to calculate an admissible estimate of the optimal cost from a given + * state to a given goal. If no cost-to-go heuristic has been specified with setCostToGoHeuristic(), this + * function just returns the identity cost, which is sure to be an admissible heuristic if there are no + * negative costs. */ + Cost costToGo(const State *state, const Goal *goal) const; + + /** \brief Defines an admissible estimate on the optimal cost on the motion between states \e s1 and \e s2. + * An admissible estimate always undervalues the true optimal cost of the motion. Used by some planners to + * speed up planning. The default implementation of this method returns this objective's identity cost, + * which is sure to be an admissible heuristic if there are no negative costs. */ + virtual Cost motionCostHeuristic(const State *s1, const State *s2) const; + + /** \brief Defines a possibly inadmissible estimate on the optimal cost on the motion between states \e s1 + * and \e s2. An inadmissible estimate does not always undervalue the true optimal cost of the motion. Used + * by some planners to + * speed up planning. The default implementation of this method returns this objective's identity cost. */ + virtual Cost motionCostBestEstimate(const State *s1, const State *s2) const; + + /** \brief Returns this objective's SpaceInformation. Needed for operators in MultiOptimizationObjective */ + const SpaceInformationPtr &getSpaceInformation() const; + + /** \brief Allocate a heuristic-sampling state generator for this cost function, defaults to a basic + * rejection sampling scheme when the derived class does not provide a better method.*/ + virtual InformedSamplerPtr allocInformedStateSampler(const ProblemDefinitionPtr &probDefn, + unsigned int maxNumberCalls) const; + + /** \brief Print information about this optimization objective */ + virtual void print(std::ostream &out) const; + + protected: + /** \brief The space information for this objective */ + SpaceInformationPtr si_; + + /** \brief The description of this optimization objective */ + std::string description_; + + /** \brief The cost threshold used for checking whether this objective has been satisfied during planning */ + Cost threshold_; + + /** \brief The function used for returning admissible estimates on the optimal cost of the path between a + * given state and goal */ + CostToGoHeuristic costToGoFn_; + }; + + /** + \brief For use when the cost-to-go of a state under the + optimization objective is equivalent to the + goal region's distanceGoal() . This function assumes that all states + within the goal region's threshold have a cost-to-go of + exactly zero. Note: \e goal is assumed to be of type + ompl::base::GoalRegion + */ + Cost goalRegionCostToGo(const State *state, const Goal *goal); + + /** \brief This class allows for the definition of multiobjective optimal planning problems. Objectives are + * added to this compound object, and motion costs are computed by taking a weighted sum of the individual + * objective costs. */ + class MultiOptimizationObjective : public OptimizationObjective + { + public: + MultiOptimizationObjective(const SpaceInformationPtr &si); + + /** \brief Adds a new objective for this multiobjective. A weight must also be specified for specifying + * importance of this objective in planning. */ + void addObjective(const OptimizationObjectivePtr &objective, double weight); + + /** \brief Returns the number of objectives that make up this multiobjective. */ + std::size_t getObjectiveCount() const; + + /** \brief Returns a specific objective from this multiobjective, where the individual objectives are in + * order of addition to the multiobjective, and \e idx is the zero-based index into this ordering. */ + const OptimizationObjectivePtr &getObjective(unsigned int idx) const; + + /** \brief Returns the weighing factor of a specific objective */ + double getObjectiveWeight(unsigned int idx) const; + + /** \brief Sets the weighing factor of a specific objective */ + void setObjectiveWeight(unsigned int idx, double weight); + + /** \brief This method "freezes" this multiobjective so that no more objectives can be added to it */ + void lock(); + + /** \brief Returns whether this multiobjective has been locked from adding further objectives */ + bool isLocked() const; + + /** The default implementation of this method is to use + addition to add up all the individual objectives' state cost + values, where each individual value is scaled by its + weight */ + Cost stateCost(const State *s) const override; + + /** The default implementation of this method is to use + addition to add up all the individual objectives' motion + cost values, where each individual value is scaled by + its weight */ + Cost motionCost(const State *s1, const State *s2) const override; + + protected: + /** \brief Defines a pairing of an objective and its weight */ + struct Component + { + Component(OptimizationObjectivePtr obj, double weight); + OptimizationObjectivePtr objective; + double weight; + }; + + /** \brief List of objective/weight pairs */ + std::vector components_; + + /** \brief Whether this multiobjective is locked from further additions */ + bool locked_; + + // Friend functions for operator overloads for easy multiobjective creation + friend OptimizationObjectivePtr operator+(const OptimizationObjectivePtr &a, + const OptimizationObjectivePtr &b); + + friend OptimizationObjectivePtr operator*(double weight, const OptimizationObjectivePtr &a); + + friend OptimizationObjectivePtr operator*(const OptimizationObjectivePtr &a, double weight); + }; + + /** \brief Given two optimization objectives, returns a MultiOptimizationObjective that combines the two + * objectives with both weights equal to 1.0. */ + OptimizationObjectivePtr operator+(const OptimizationObjectivePtr &a, const OptimizationObjectivePtr &b); + + /** \brief Given a weighing factor and an optimization objective, returns a MultiOptimizationObjective + * containing only this objective weighted by the given weight */ + OptimizationObjectivePtr operator*(double weight, const OptimizationObjectivePtr &a); + + /** \brief Given a weighing factor and an optimization objective, returns a MultiOptimizationObjective + * containing only this objective weighted by the given weight */ + OptimizationObjectivePtr operator*(const OptimizationObjectivePtr &a, double weight); + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h new file mode 100644 index 00000000..ab222f2c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h @@ -0,0 +1,128 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_PATH_ +#define OMPL_BASE_PATH_ + +#include "ompl/util/ClassForward.h" +#include "ompl/base/Cost.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /// @cond IGNORE + OMPL_CLASS_FORWARD(OptimizationObjective); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::Path */ + OMPL_CLASS_FORWARD(Path); + /// @endcond + + /** \class ompl::base::PathPtr + \brief A shared pointer wrapper for ompl::base::Path */ + + /** \brief Abstract definition of a path */ + class Path + { + public: + // non-copyable + Path(const Path &) = delete; + Path &operator=(const Path &) = delete; + + /** \brief Constructor. A path must always know the space information it is part of */ + Path(SpaceInformationPtr si) : si_(std::move(si)) + { + } + + /** \brief Destructor */ + virtual ~Path() = default; + + /** \brief Get the space information associated to this class */ + const SpaceInformationPtr &getSpaceInformation() const + { + return si_; + } + + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are allocating is indeed a Path */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are allocating is indeed a Path */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Return the length of a path */ + virtual double length() const = 0; + + /** \brief Return the cost of the path with respect to a + specified optimization objective. */ + virtual Cost cost(const OptimizationObjectivePtr &obj) const = 0; + + /** \brief Check if the path is valid */ + virtual bool check() const = 0; + + /** \brief Print the path to a stream */ + virtual void print(std::ostream &out) const = 0; + + protected: + /** \brief The space information this path is part of */ + SpaceInformationPtr si_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h new file mode 100644 index 00000000..28356daa --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h @@ -0,0 +1,432 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_PLANNER_ +#define OMPL_BASE_PLANNER_ + +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/ProblemDefinition.h" +#include "ompl/base/PlannerData.h" +#include "ompl/base/PlannerStatus.h" +#include "ompl/base/PlannerTerminationCondition.h" +#include "ompl/base/GenericParam.h" +#include "ompl/util/Console.h" +#include "ompl/util/Time.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::Planner */ + OMPL_CLASS_FORWARD(Planner); + /// @endcond + + /** \class ompl::base::PlannerPtr + \brief A shared pointer wrapper for ompl::base::Planner */ + + /** \brief Helper class to extract valid start & goal + states. Usually used internally by planners. + + This class is meant to behave correctly if the user + updates the problem definition between subsequent calls to + ompl::base::Planner::solve() \b without calling + ompl::base::Planner::clear() in between. Only allowed + changes to the problem definition are accounted for: + adding of starring states or adding of goal states for + instances inherited from + ompl::base::GoalSampleableRegion. */ + class PlannerInputStates + { + public: + /** \brief Default constructor. No work is performed. */ + PlannerInputStates(const PlannerPtr &planner) : planner_(planner.get()) + { + tempState_ = nullptr; + update(); + } + + /** \brief Default constructor. No work is performed. */ + PlannerInputStates(const Planner *planner) : planner_(planner) + { + tempState_ = nullptr; + update(); + } + + /** \brief Default constructor. No work is performed. A + call to use() needs to be made, before making any + calls to nextStart() or nextGoal(). */ + PlannerInputStates() + { + tempState_ = nullptr; + clear(); + } + + /** \brief Destructor. Clear allocated memory. */ + ~PlannerInputStates() + { + clear(); + } + + /** \brief Clear all stored information. */ + void clear(); + + /** \brief Forget how many states were returned by + nextStart() and nextGoal() and return all states + again */ + void restart(); + + /** \brief Set the space information and problem + definition this class operates on, based on the + available planner instance. Returns true if changes + were found (different problem definition) and clear() + was called. */ + bool update(); + + /** \brief Set the problem definition this class operates on. + If a planner is not set in the constructor argument, a call + to this function is needed before any calls to nextStart() + or nextGoal() are made. Returns true if changes were found + (different problem definition) and clear() was called. */ + bool use(const ProblemDefinitionPtr &pdef); + + /** \brief Check if the problem definition was set, start + state are available and goal was set */ + void checkValidity() const; + + /** \brief Return the next valid start state or nullptr if no + more valid start states are available. */ + const State *nextStart(); + + /** \brief Return the next valid goal state or nullptr if no + more valid goal states are available. Because + sampling of goal states may also produce invalid + goals, this function takes an argument that specifies + whether a termination condition has been reached. If + the termination condition evaluates to true the + function terminates even if no valid goal has been + found. */ + const State *nextGoal(const PlannerTerminationCondition &ptc); + + /** \brief Same as above but only one attempt is made to find a valid goal. */ + const State *nextGoal(); + + /** \brief Check if there are more potential start states */ + bool haveMoreStartStates() const; + + /** \brief Check if there are more potential goal states */ + bool haveMoreGoalStates() const; + + /** \brief Get the number of start states from the problem + definition that were already seen, including invalid + ones. */ + unsigned int getSeenStartStatesCount() const + { + return addedStartStates_; + } + + /** \brief Get the number of sampled goal states, including invalid ones */ + unsigned int getSampledGoalsCount() const + { + return sampledGoalsCount_; + } + + private: + const Planner *planner_{nullptr}; + + unsigned int addedStartStates_; + unsigned int sampledGoalsCount_; + State *tempState_; + + ProblemDefinitionPtr pdef_; + const SpaceInformation *si_; + }; + + /** \brief Properties that planners may have */ + struct PlannerSpecs + { + PlannerSpecs() = default; + + /** \brief The type of goal specification the planner can use */ + GoalType recognizedGoal{GOAL_ANY}; + + /** \brief Flag indicating whether multiple threads are used in the computation of the planner */ + bool multithreaded{false}; + + /** \brief Flag indicating whether the planner is able to compute approximate solutions */ + bool approximateSolutions{false}; + + /** \brief Flag indicating whether the planner attempts to optimize the path and reduce its length until the + maximum path length specified by the goal representation is satisfied */ + bool optimizingPaths{false}; + + /** \brief Flag indicating whether the planner is able to account for the fact that the validity of a motion + from A to B may not be the same as the validity of a motion from B to A. + If this flag is true, the planner will return solutions that do not make this assumption. Usually + roadmap-based planners make this assumption and tree-based planners do not. */ + bool directed{false}; + + /** \brief Flag indicating whether the planner is able to prove that no solution path exists. */ + bool provingSolutionNonExistence{false}; + + /** \brief Flag indicating whether the planner is able to report the computation of intermediate paths. */ + bool canReportIntermediateSolutions{false}; + }; + + /** \brief Base class for a planner */ + class Planner + { + public: + // non-copyable + Planner(const Planner &) = delete; + Planner &operator=(const Planner &) = delete; + + /** \brief Constructor */ + Planner(SpaceInformationPtr si, std::string name); + + /** \brief Destructor */ + virtual ~Planner() = default; + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are casting to is indeed a planner */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are casting to is indeed a Planner */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Get the space information this planner is using */ + const SpaceInformationPtr &getSpaceInformation() const; + + /** \brief Get the problem definition the planner is trying to solve */ + const ProblemDefinitionPtr &getProblemDefinition() const; + + /** \brief Get the problem definition the planner is trying to solve */ + ProblemDefinitionPtr &getProblemDefinition(); + + /** \brief Get the planner input states */ + const PlannerInputStates &getPlannerInputStates() const; + + /** \brief Set the problem definition for the planner. The + problem needs to be set before calling solve(). Note: + If this problem definition replaces a previous one, it + may also be necessary to call clear() or clearQuery(). */ + virtual void setProblemDefinition(const ProblemDefinitionPtr &pdef); + + /** \brief Function that can solve the motion planning problem. This + function can be called multiple times on the same problem, + without calling clear() in between. This allows the planner to + continue work for more time on an unsolved problem, for example. + If this option is used, it is assumed the problem definition is + not changed (unpredictable results otherwise). The only change + in the problem definition that is accounted for is the addition + of starting or goal states (but not changing previously added + start/goal states). If clearQuery() is called, the planner may + retain prior datastructures generated from a previous query on a + new problem definition. The function terminates if the call to + \e ptc returns true. */ + virtual PlannerStatus solve(const PlannerTerminationCondition &ptc) = 0; + + /** \brief Same as above except the termination condition + is only evaluated at a specified interval. */ + PlannerStatus solve(const PlannerTerminationConditionFn &ptc, double checkInterval); + + /** \brief Same as above except the termination condition + is solely a time limit: the number of seconds the + algorithm is allowed to spend planning. */ + PlannerStatus solve(double solveTime); + + /** \brief Clear all internal datastructures. Planner + settings are not affected. Subsequent calls to solve() + will ignore all previous work. */ + virtual void clear(); + + /** \brief Clears internal datastructures of any query-specific + information from the previous query. Planner settings are not + affected. The planner, if able, should retain all datastructures + generated from previous queries that can be used to help solve + the next query. Note that clear() should also clear all + query-specific information along with all other datastructures + in the planner. By default clearQuery() calls clear(). */ + virtual void clearQuery(); + + /** \brief Get information about the current run of the + motion planner. Repeated calls to this function will + update \e data (only additions are made). This is + useful to see what changed in the exploration + datastructure, between calls to solve(), for example + (without calling clear() in between). */ + virtual void getPlannerData(PlannerData &data) const; + + /** \brief Get the name of the planner */ + const std::string &getName() const; + + /** \brief Set the name of the planner */ + void setName(const std::string &name); + + /** \brief Return the specifications (capabilities of this planner) */ + const PlannerSpecs &getSpecs() const; + + /** \brief Perform extra configuration steps, if + needed. This call will also issue a call to + ompl::base::SpaceInformation::setup() if needed. This + must be called before solving */ + virtual void setup(); + + /** \brief Check to see if the planner is in a working + state (setup has been called, a goal was set, the + input states seem to be in order). In case of error, + this function throws an exception.*/ + virtual void checkValidity(); + + /** \brief Check if setup() was called for this planner */ + bool isSetup() const; + + /** \brief Get the parameters for this planner */ + ParamSet ¶ms() + { + return params_; + } + + /** \brief Get the parameters for this planner */ + const ParamSet ¶ms() const + { + return params_; + } + + /** \brief Definition of a function which returns a property about the planner's progress that can be + * queried by a benchmarking routine */ + using PlannerProgressProperty = std::function; + + /** \brief A dictionary which maps the name of a progress property to the function to be used for querying + * that property */ + using PlannerProgressProperties = std::map; + + /** \brief Retrieve a planner's planner progress property map */ + const PlannerProgressProperties &getPlannerProgressProperties() const + { + return plannerProgressProperties_; + } + + /** \brief Print properties of the motion planner */ + virtual void printProperties(std::ostream &out) const; + + /** \brief Print information about the motion planner's settings */ + virtual void printSettings(std::ostream &out) const; + + protected: + /** \brief This function declares a parameter for this planner instance, and specifies the setter and getter + * functions. */ + template + void declareParam(const std::string &name, const PlannerType &planner, const SetterType &setter, + const GetterType &getter, const std::string &rangeSuggestion = "") + { + params_.declareParam( + name, [planner, setter](T param) { (*planner.*setter)(param); }, + [planner, getter] { return (*planner.*getter)(); }); + if (!rangeSuggestion.empty()) + params_[name].setRangeSuggestion(rangeSuggestion); + } + + /** \brief This function declares a parameter for this planner instance, and specifies the setter function. + */ + template + void declareParam(const std::string &name, const PlannerType &planner, const SetterType &setter, + const std::string &rangeSuggestion = "") + { + params_.declareParam(name, [planner, setter](T param) { (*planner.*setter)(param); }); + if (!rangeSuggestion.empty()) + params_[name].setRangeSuggestion(rangeSuggestion); + } + + /** \brief Add a planner progress property called \e progressPropertyName with a property querying function + * \e prop to this planner's progress property map */ + void addPlannerProgressProperty(const std::string &progressPropertyName, + const PlannerProgressProperty &prop) + { + plannerProgressProperties_[progressPropertyName] = prop; + } + + /** \brief The space information for which planning is done */ + SpaceInformationPtr si_; + + /** \brief The user set problem definition */ + ProblemDefinitionPtr pdef_; + + /** \brief Utility class to extract valid input states */ + PlannerInputStates pis_; + + /** \brief The name of this planner */ + std::string name_; + + /** \brief The specifications of the planner (its capabilities) */ + PlannerSpecs specs_; + + /** \brief A map from parameter names to parameter instances for this planner. This field is populated by + * the declareParam() function */ + ParamSet params_; + + /** \brief A mapping between this planner's progress property names and the functions used for querying + * those progress properties */ + PlannerProgressProperties plannerProgressProperties_; + + /** \brief Flag indicating whether setup() has been called */ + bool setup_; + }; + + /** \brief Definition of a function that can allocate a planner */ + using PlannerAllocator = std::function; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h new file mode 100644 index 00000000..ca8bae44 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h @@ -0,0 +1,437 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna, Luis G. Torres */ + +#ifndef OMPL_BASE_PLANNER_DATA_ +#define OMPL_BASE_PLANNER_DATA_ + +#include +#include +#include +#include +#include "ompl/base/State.h" +#include "ompl/base/Cost.h" +#include "ompl/base/SpaceInformation.h" +#include "ompl/util/ClassForward.h" +#include + +namespace ompl +{ + namespace base + { + /// \brief Base class for a vertex in the PlannerData structure. All + /// derived classes must implement the clone and equivalence operators. + /// It is assumed that each vertex in the PlannerData structure is + /// unique (i.e. no duplicates allowed). + class PlannerDataVertex + { + public: + /// \brief Constructor. Takes a state pointer and an optional integer tag. + PlannerDataVertex(const State *st, int tag = 0) : state_(st), tag_(tag) + { + } + /// \brief Copy constructor. + PlannerDataVertex(const PlannerDataVertex &rhs) = default; + virtual ~PlannerDataVertex() = default; + + /// \brief Returns the integer tag associated with this vertex. + virtual int getTag() const + { + return tag_; + } + /// \brief Set the integer tag associated with this vertex. + virtual void setTag(int tag) + { + tag_ = tag; + } + /// \brief Retrieve the state associated with this vertex. + virtual const State *getState() const + { + return state_; + } + + /// \brief Return a clone of this object, allocated from the heap. + virtual PlannerDataVertex *clone() const + { + return new PlannerDataVertex(*this); + } + + /// \brief Equivalence operator. Return true if the state pointers are equal. + virtual bool operator==(const PlannerDataVertex &rhs) const + { + // States should be unique + return state_ == rhs.state_; + } + + /// \brief Returns true if this vertex is not equal to the argument. + /// This is the complement of the == operator. + bool operator!=(const PlannerDataVertex &rhs) const + { + return !(*this == rhs); + } + + protected: + PlannerDataVertex() = default; + + friend class boost::serialization::access; + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar & tag_; + // Serialization of the state pointer is handled by PlannerDataStorage + } + + /// \brief The state represented by this vertex + const State *state_; + /// \brief A generic integer tag for this state. Not used for equivalence checking. + int tag_; + + friend class PlannerData; + friend class PlannerDataStorage; + }; + + /// \brief Base class for a PlannerData edge. + class PlannerDataEdge + { + public: + PlannerDataEdge() = default; + virtual ~PlannerDataEdge() = default; + /// \brief Return a clone of this object, allocated from the heap. + virtual PlannerDataEdge *clone() const + { + return new PlannerDataEdge(); + } + + /// \brief Returns true if the edges point to the same memory + virtual bool operator==(const PlannerDataEdge &rhs) const + { + return this == &rhs; + } + + /// \brief Returns true if the edges do not point to the same memory. + /// This is the complement of the == operator. + bool operator!=(const PlannerDataEdge &rhs) const + { + return !(*this == rhs); + } + + protected: + friend class boost::serialization::access; + template + void serialize(Archive & /*ar*/, const unsigned int /*version*/) + { + } + }; + + /// @cond IGNORE + OMPL_CLASS_FORWARD(StateStorage); + OMPL_CLASS_FORWARD(PlannerData); + + // Forward declaration for PlannerData::computeEdgeWeights + class OptimizationObjective; + /// @endcond + + /** \class ompl::base::PlannerDataPtr + \brief A shared pointer wrapper for ompl::base::PlannerData */ + + /// \brief Object containing planner generated vertex and edge data. It + /// is assumed that all vertices are unique, and only a single directed + /// edge connects two vertices. + /// \note The storage for states this class maintains belongs to the planner + /// instance that filled the data (by default; see PlannerData::decoupleFromPlanner()) + class PlannerData + { + public: + class Graph; + + /// \brief Representation for a non-existant edge + static const PlannerDataEdge NO_EDGE; + /// \brief Representation for a non-existant vertex + static const PlannerDataVertex NO_VERTEX; + /// \brief Representation of an invalid vertex index + static const unsigned int INVALID_INDEX; + + // non-copyable + PlannerData(const PlannerData &) = delete; + PlannerData &operator=(const PlannerData &) = delete; + + /// \brief Constructor. Accepts a SpaceInformationPtr for the space planned in. + PlannerData(SpaceInformationPtr si); + /// \brief Destructor. + virtual ~PlannerData(); + + /// \name PlannerData construction + /// \{ + + /// \brief Adds the given vertex to the graph data. The vertex index + /// is returned. Duplicates are not added. If a vertex is duplicated, + /// the index of the existing vertex is returned instead. + /// Indexes are volatile and may change after adding/removing a subsequent vertex. + unsigned int addVertex(const PlannerDataVertex &st); + /// \brief Adds the given vertex to the graph data, and marks it as a + /// start vertex. The vertex index is returned. Duplicates are not added. + /// If a vertex is duplicated, the index of the existing vertex is returned instead. + /// Indexes are volatile and may change after adding/removing a subsequent vertex. + unsigned int addStartVertex(const PlannerDataVertex &v); + /// \brief Adds the given vertex to the graph data, and marks it as a + /// start vertex. The vertex index is returned. Duplicates are not added. + /// If a vertex is duplicated, the index of the existing vertex is returned instead. + /// Indexes are volatile and may change after adding/removing a subsequent vertex. + unsigned int addGoalVertex(const PlannerDataVertex &v); + /// \brief Mark the given state as a start vertex. If the given state does not exist in a + /// vertex, false is returned. + bool markStartState(const State *st); + /// \brief Mark the given state as a goal vertex. If the given state does not exist in a + /// vertex, false is returned. + bool markGoalState(const State *st); + /// \brief Set the integer tag associated with the given state. If the given + /// state does not exist in a vertex, false is returned. + bool tagState(const State *st, int tag); + /// \brief Removes the vertex associated with the given data. If the + /// vertex does not exist, false is returned. + /// This method has O(n) complexity in the number of vertices. + virtual bool removeVertex(const PlannerDataVertex &st); + /// \brief Removes the vertex with the given index. If the index is + /// out of range, false is returned. + /// This method has O(n) complexity in the number of vertices. + virtual bool removeVertex(unsigned int vIndex); + /// \brief Adds a directed edge between the given vertex indexes. An optional + /// edge structure and weight can be supplied. Success is returned. + virtual bool addEdge(unsigned int v1, unsigned int v2, const PlannerDataEdge &edge = PlannerDataEdge(), + Cost weight = Cost(1.0)); + /// \brief Adds a directed edge between the given vertex indexes. The + /// vertices are added to the data if they are not already in the + /// structure. An optional edge structure and weight can also be supplied. + /// Success is returned. + virtual bool addEdge(const PlannerDataVertex &v1, const PlannerDataVertex &v2, + const PlannerDataEdge &edge = PlannerDataEdge(), Cost weight = Cost(1.0)); + /// \brief Removes the edge between vertex indexes \e v1 and \e v2. Success is returned. + virtual bool removeEdge(unsigned int v1, unsigned int v2); + /// \brief Removes the edge between the vertices associated with the given vertex data. + /// Success is returned. + virtual bool removeEdge(const PlannerDataVertex &v1, const PlannerDataVertex &v2); + /// \brief Clears the entire data structure + virtual void clear(); + /// \brief Creates a deep copy of the states contained in the vertices of this + /// PlannerData structure so that when the planner that created this instance goes + /// out of scope, all data remains intact. + /// \remarks Shallow state pointers inside of the PlannerDataVertex objects already + /// in this PlannerData will be replaced with clones which are scoped to this PlannerData + /// object. A subsequent call to this method is necessary after any other vertices are + /// added to ensure that this PlannerData instance is fully decoupled. + virtual void decoupleFromPlanner(); + + /// \} + /// \name PlannerData Properties + /// \{ + + /// \brief Retrieve the number of edges in this structure + unsigned int numEdges() const; + /// \brief Retrieve the number of vertices in this structure + unsigned int numVertices() const; + /// \brief Returns the number of start vertices + unsigned int numStartVertices() const; + /// \brief Returns the number of goal vertices + unsigned int numGoalVertices() const; + + /// \} + /// \name PlannerData vertex lookup + /// \{ + + /// \brief Check whether a vertex exists with the given vertex data + bool vertexExists(const PlannerDataVertex &v) const; + /// \brief Retrieve a reference to the vertex object with the given + /// index. If this vertex does not exist, NO_VERTEX is returned. + const PlannerDataVertex &getVertex(unsigned int index) const; + /// \brief Retrieve a reference to the vertex object with the given + /// index. If this vertex does not exist, NO_VERTEX is returned. + PlannerDataVertex &getVertex(unsigned int index); + /// \brief Retrieve a reference to the ith start vertex object. If + /// \e i is greater than the number of start vertices, NO_VERTEX is returned. + const PlannerDataVertex &getStartVertex(unsigned int i) const; + /// \brief Retrieve a reference to the ith start vertex object. If + /// \e i is greater than the number of start vertices, NO_VERTEX is returned. + PlannerDataVertex &getStartVertex(unsigned int i); + /// \brief Retrieve a reference to the ith goal vertex object. If + /// \e i is greater than the number of goal vertices, NO_VERTEX is returned. + const PlannerDataVertex &getGoalVertex(unsigned int i) const; + /// \brief Retrieve a reference to the ith goal vertex object. If + /// \e i is greater than the number of goal vertices, NO_VERTEX is returned. + PlannerDataVertex &getGoalVertex(unsigned int i); + /// \brief Returns the index of the ith start state. + /// INVALID_INDEX is returned if \e i is out of range. + /// Indexes are volatile and may change after adding/removing a vertex. + unsigned int getStartIndex(unsigned int i) const; + /// \brief Returns the index of the ith goal state. + /// INVALID_INDEX is returned if \e i is out of range + /// Indexes are volatile and may change after adding/removing a vertex. + unsigned int getGoalIndex(unsigned int i) const; + /// \brief Returns true if the given vertex index is marked as a start vertex + bool isStartVertex(unsigned int index) const; + /// \brief Returns true if the given vertex index is marked as a goal vertex + bool isGoalVertex(unsigned int index) const; + /// \brief Return the index for the vertex associated with the given data. + /// INVALID_INDEX is returned if this vertex does not exist. + /// Indexes are volatile and may change after adding/removing a vertex. + unsigned int vertexIndex(const PlannerDataVertex &v) const; + + /// \} + /// \name PlannerData edge lookup + /// \{ + + /// \brief Check whether an edge between vertex index \e v1 and index \e v2 exists + bool edgeExists(unsigned int v1, unsigned int v2) const; + /// \brief Retrieve a reference to the edge object connecting vertices + /// with indexes \e v1 and \e v2. If this edge does not exist, NO_EDGE is returned. + const PlannerDataEdge &getEdge(unsigned int v1, unsigned int v2) const; + /// \brief Retrieve a reference to the edge object connecting vertices + /// with indexes \e v1 and \e v2. If this edge does not exist, NO_EDGE is returned. + PlannerDataEdge &getEdge(unsigned int v1, unsigned int v2); + /// \brief Returns a list of the vertex indexes directly connected to + /// vertex with index \e v (outgoing edges). The number of outgoing + /// edges from \e v is returned. + unsigned int getEdges(unsigned int v, std::vector &edgeList) const; + /// \brief Returns a map of outgoing edges from vertex with index \e v. + /// Key = vertex index, value = edge structure. The number of outgoing edges from \e v is returned + unsigned int getEdges(unsigned int v, std::map &edgeMap) const; + /// \brief Returns a list of vertices with outgoing edges to the vertex with index \e v. + /// The number of edges connecting to \e v is returned. + unsigned int getIncomingEdges(unsigned int v, std::vector &edgeList) const; + /// \brief Returns a map of incoming edges to the vertex with index \e v (i.e. if there is an + /// edge from w to v, w and the edge structure will be in the map.) + /// Key = vertex index, value = edge structure. The number of incoming edges to \e v is returned + unsigned int getIncomingEdges(unsigned int v, + std::map &edgeMap) const; + /// \brief Returns the weight of the edge between the + /// given vertex indices. If there exists an edge between + /// \e v1 and \v2, the edge weight is placed in the + /// out-variable \e weight. Otherwise, this function + /// returns false. + bool getEdgeWeight(unsigned int v1, unsigned int v2, Cost *weight) const; + /// \brief Sets the weight of the edge between the given + /// vertex indices. If an edge between v1 and v2 does not + /// exist, this function returns false. + bool setEdgeWeight(unsigned int v1, unsigned int v2, Cost weight); + /// \brief Computes the weight for all edges given the + /// OptimizationObjective \e opt. + void computeEdgeWeights(const OptimizationObjective &opt); + /// \brief Computes all edge weights using state space + /// distance (i.e. getSpaceInformation()->distance()) + void computeEdgeWeights(); + + /// \} + /// \name Output methods + /// \{ + + /// \brief Writes a Graphviz dot file of this structure to the given stream + void printGraphviz(std::ostream &out = std::cout) const; + + /// \brief Writes a GraphML file of this structure to the given stream + void printGraphML(std::ostream &out = std::cout) const; + + /** \brief Write a mesh of the planner graph to a stream. Insert + * additional vertices if \a asIs == true. */ + void printPLY(std::ostream &out, bool asIs = false) const; + + /// \} + /// \name Advanced graph extraction + /// \{ + + /// \brief Extracts the minimum spanning tree of the data rooted at the vertex + /// with index \e v. The minimum spanning tree is saved into \e mst. + /// O(|E| log |V|) complexity. + void extractMinimumSpanningTree(unsigned int v, const OptimizationObjective &opt, PlannerData &mst) const; + /// \brief Extracts the subset of PlannerData reachable from the vertex with index + /// v. For tree structures, this will be the sub-tree rooted at v. The reachable set + /// is saved into \e data. + void extractReachable(unsigned int v, PlannerData &data) const; + + /// \brief Extract a ompl::base::GraphStateStorage object from this PlannerData. Memory for states is copied + /// (the resulting ompl::base::StateStorage is independent from this PlannerData) + StateStoragePtr extractStateStorage() const; + + /// \brief Extract a Boost.Graph object from this PlannerData. + /// \remarks Use of this method requires inclusion of PlannerDataGraph.h The object + /// returned can be used safely for all read-only purposes in Boost. Adding or + /// removing vertices and edges should be performed by using the respective method + /// in PlannerData to ensure proper memory management. Manipulating the graph directly + /// will result in undefined behavior with this class. + Graph &toBoostGraph(); + /// \brief Extract a Boost.Graph object from this PlannerData. + /// \remarks Use of this method requires inclusion of PlannerDataGraph.h The object + /// returned can be used safely for all read-only purposes in Boost. Adding or + /// removing vertices and edges should be performed by using the respective method + /// in PlannerData to ensure proper memory management. Manipulating the graph directly + /// will result in undefined behavior with this class. + const Graph &toBoostGraph() const; + + /// \} + + /// \brief Return the instance of SpaceInformation used in this PlannerData + const SpaceInformationPtr &getSpaceInformation() const; + + /// \brief Indicate whether any information about controls (ompl::control::Control) is stored in this + /// instance + virtual bool hasControls() const; + + /// \brief Any extra properties (key-value pairs) the planner can set. + std::map properties; + + protected: + /// \brief A mapping of states to vertex indexes. For fast lookup of vertex index. + std::map stateIndexMap_; + /// \brief A mutable listing of the vertices marked as start states. Stored in sorted order. + std::vector startVertexIndices_; + /// \brief A mutable listing of the vertices marked as goal states. Stored in sorted order. + std::vector goalVertexIndices_; + + /// \brief The space information instance for this data. + SpaceInformationPtr si_; + /// \brief A list of states that are allocated during the decoupleFromPlanner method. + /// These states are freed by PlannerData in the destructor. + std::set decoupledStates_; + + private: + void freeMemory(); + + // Abstract pointer that points to the Boost.Graph structure. + // Obscured to prevent unnecessary inclusion of BGL throughout the + // rest of the code. + void *graphRaw_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h new file mode 100644 index 00000000..8ebbd79e --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h @@ -0,0 +1,94 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_BASE_PLANNER_DATA_GRAPH_ +#define OMPL_BASE_PLANNER_DATA_GRAPH_ + +#include "ompl/base/PlannerData.h" +#include "ompl/base/Cost.h" + +#include +#include + +/// @cond IGNORE +// Installing custom vertex and edge properties +enum edge_type_t +{ + edge_type +}; +enum vertex_type_t +{ + vertex_type +}; +namespace boost +{ + BOOST_INSTALL_PROPERTY(edge, type); + BOOST_INSTALL_PROPERTY(vertex, type); +} // namespace boost + +using PlannerDataGraph = + boost::adjacency_list>, + boost::property>>; +/// @endcond + +/// \brief Wrapper class for the Boost.Graph representation of the PlannerData. +/// This class inherits from a boost::adjacency_list Graph structure. +class ompl::base::PlannerData::Graph : public PlannerDataGraph +{ +public: + /// \brief Data type for the Boost.Graph representation. + using Type = PlannerDataGraph; + + /// \brief Boost.Graph vertex descriptor + using Vertex = boost::graph_traits::vertex_descriptor; + /// \brief Boost.Graph edge descriptor + using Edge = boost::graph_traits::edge_descriptor; + /// \brief Boost.Graph vertex iterator + using VIterator = boost::graph_traits::vertex_iterator; + /// \brief Boost.Graph edge iterator + using EIterator = boost::graph_traits::edge_iterator; + /// \brief Boost.Graph input edge iterator + using IEIterator = boost::graph_traits::in_edge_iterator; + /// \brief Boost.Graph output edge iterator + using OEIterator = boost::graph_traits::out_edge_iterator; + /// \brief Boost.Graph adjacency iterator + using AdjIterator = boost::graph_traits::adjacency_iterator; +}; + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h new file mode 100644 index 00000000..1d8e02b9 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h @@ -0,0 +1,294 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_BASE_PLANNER_DATA_STORAGE_ +#define OMPL_BASE_PLANNER_DATA_STORAGE_ + +#include "ompl/base/PlannerData.h" +#include "ompl/util/Console.h" +#include +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// \brief Object that handles loading/storing a PlannerData object to/from a binary stream. + /// Serialization of vertices and edges is performed using the Boost archive method + /// \e serialize. Derived vertex/edge classes are handled, presuming those classes implement + /// the \e serialize method. + /// \remarks Since the \e serialize method for vertices and edges is templated, it cannot + /// be virtual. To serialize a derived class AND the base class data, a special call can + /// be invoked inside of \e serialize that instructs the serializer to also serialize the + /// base class. The derived class must also have a GUID exposed to the serializer + /// for proper deserialization at runtime. This is performed with the \e BOOST_CLASS_EXPORT + /// macro. An example of these items is given below: + /// \code + /// #include + /// + /// class MyVertexClass : public ompl::base::PlannerDataVertex + /// { + /// // ---SNIP--- + /// + /// template + /// void serialize(Archive & ar, const unsigned int version) + /// { + /// ar & boost::serialization::base_object(*this); + /// // ... (The other members of MyVertexClass) + /// } + /// }; + /// + /// BOOST_CLASS_EXPORT(MyVertexClass); + /// \endcode + class PlannerDataStorage + { + public: + /// \brief Default constructor. + PlannerDataStorage(); + /// \brief Destructor + virtual ~PlannerDataStorage(); + + /// \brief Store (serialize) the PlannerData structure to the given filename. + /// \return True on success, false on failure. + virtual bool store(const PlannerData &pd, const char *filename); + + /// \brief Store (serialize) the PlannerData structure to the given stream. + /// \return True on success, false on failure. + virtual bool store(const PlannerData &pd, std::ostream &out); + + /// \brief Load the PlannerData structure from the given stream. + /// The StateSpace that was used to store the data must match the + /// StateSpace inside of the argument PlannerData. + /// \return True on success, false on failure. + virtual bool load(const char *filename, PlannerData &pd); + + /// \brief Load the PlannerData structure from the given stream. + /// The StateSpace that was used to store the data must match the + /// StateSpace inside of the argument PlannerData. + /// \return True on success, false on failure. + virtual bool load(std::istream &in, PlannerData &pd); + + protected: + /// \brief Information stored at the beginning of the PlannerData archive + struct Header + { + /// \brief OMPL PlannerData specific marker (fixed value) + std::uint_fast32_t marker; + + /// \brief Number of vertices stored in the archive + std::size_t vertex_count; + + /// \brief Number of edges stored in the archive + std::size_t edge_count; + + /// \brief Signature of state space that allocated the saved states in the vertices (see + /// ompl::base::StateSpace::computeSignature()) */ + std::vector signature; + + /// \brief boost::serialization routine + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar & marker; + ar & vertex_count; + ar & edge_count; + ar & signature; + } + }; + + /// \brief The object containing all vertex data that will be stored + struct PlannerDataVertexData + { + enum VertexType + { + STANDARD = 0, + START, + GOAL + }; + + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar & v_; + ar & state_; + ar & type_; + } + + const PlannerDataVertex *v_; + std::vector state_; + VertexType type_; + }; + + /// \brief The object containing all edge data that will be stored + struct PlannerDataEdgeData + { + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar & e_; + ar & endpoints_; + ar & weight_; + } + + const PlannerDataEdge *e_; + std::pair endpoints_; + double weight_; + }; + + /// \brief Read \e numVertices from the binary input \e ia and store them as PlannerData. + virtual void loadVertices(PlannerData &pd, unsigned int numVertices, boost::archive::binary_iarchive &ia) + { + const StateSpacePtr &space = pd.getSpaceInformation()->getStateSpace(); + std::vector states; + for (unsigned int i = 0; i < numVertices; ++i) + { + PlannerDataVertexData vertexData; + ia >> vertexData; + + // Deserializing all data in the vertex (except the state) + const PlannerDataVertex *v = vertexData.v_; + + // Allocating a new state and deserializing it from the buffer + State *state = space->allocState(); + states.push_back(state); + space->deserialize(state, &vertexData.state_[0]); + const_cast(v)->state_ = state; + + // Record the type of the vertex (i.e. start vertex). + if (vertexData.type_ == PlannerDataVertexData::START) + pd.addStartVertex(*v); + else if (vertexData.type_ == PlannerDataVertexData::GOAL) + pd.addGoalVertex(*v); + else + pd.addVertex(*v); + + // We deserialized the vertex object pointer, and we own it. + // Since addEdge copies the object, it is safe to free here. + delete vertexData.v_; + } + + // These vertices are using state pointers allocated here. + // To avoid a memory leak, we decouple planner data from the + // 'planner', which will clone all states and properly free the + // memory when PlannerData goes out of scope. Then it is safe + // to free all memory allocated here. + pd.decoupleFromPlanner(); + + for (auto &state : states) + space->freeState(state); + } + + /// \brief Serialize and store all vertices in \e pd to the binary archive. + virtual void storeVertices(const PlannerData &pd, boost::archive::binary_oarchive &oa) + { + const StateSpacePtr &space = pd.getSpaceInformation()->getStateSpace(); + std::vector state(space->getSerializationLength()); + for (unsigned int i = 0; i < pd.numVertices(); ++i) + { + PlannerDataVertexData vertexData; + + // Serializing all data in the vertex (except the state) + const PlannerDataVertex &v = pd.getVertex(i); + vertexData.v_ = &v; + + // Record the type of the vertex (i.e. start vertex). + if (pd.isStartVertex(i)) + vertexData.type_ = PlannerDataVertexData::START; + else if (pd.isGoalVertex(i)) + vertexData.type_ = PlannerDataVertexData::GOAL; + else + vertexData.type_ = PlannerDataVertexData::STANDARD; + + // Serializing the state contained in this vertex + space->serialize(&state[0], v.getState()); + vertexData.state_ = state; + + oa << vertexData; + } + } + + /// \brief Read \e numEdges from the binary input \e ia and store them as PlannerData. + virtual void loadEdges(PlannerData &pd, unsigned int numEdges, boost::archive::binary_iarchive &ia) + { + for (unsigned int i = 0; i < numEdges; ++i) + { + PlannerDataEdgeData edgeData; + ia >> edgeData; + pd.addEdge(edgeData.endpoints_.first, edgeData.endpoints_.second, *edgeData.e_, + Cost(edgeData.weight_)); + + // We deserialized the edge object pointer, and we own it. + // Since addEdge copies the object, it is safe to free here. + delete edgeData.e_; + } + } + + /// \brief Serialize and store all edges in \e pd to the binary archive. + virtual void storeEdges(const PlannerData &pd, boost::archive::binary_oarchive &oa) + { + std::vector edgeList; + for (unsigned int fromVertex = 0; fromVertex < pd.numVertices(); ++fromVertex) + { + edgeList.clear(); + pd.getEdges(fromVertex, edgeList); // returns the id of each edge + + // Process edges + for (unsigned int toVertex : edgeList) + { + // Get cost + Cost weight; + if (!pd.getEdgeWeight(fromVertex, toVertex, &weight)) + OMPL_ERROR("Unable to get edge weight"); + + // Convert to new structure + PlannerDataEdgeData edgeData; + edgeData.e_ = &pd.getEdge(fromVertex, toVertex); + edgeData.endpoints_.first = fromVertex; + edgeData.endpoints_.second = toVertex; + edgeData.weight_ = weight.value(); + oa << edgeData; + + } // for each edge + } // for each vertex + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h new file mode 100644 index 00000000..d32c7fb9 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h @@ -0,0 +1,115 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_PLANNER_STATUS_ +#define OMPL_BASE_PLANNER_STATUS_ + +#include +#include + +namespace ompl +{ + namespace base + { + /// A class to store the exit status of Planner::solve() + struct PlannerStatus + { + /// The possible values of the status returned by a planner + enum StatusType + { + /// Uninitialized status + UNKNOWN = 0, + /// Invalid start state or no start state specified + INVALID_START, + /// Invalid goal state + INVALID_GOAL, + /// The goal is of a type that a planner does not recognize + UNRECOGNIZED_GOAL_TYPE, + /// The planner failed to find a solution + TIMEOUT, + /// The planner found an approximate solution + APPROXIMATE_SOLUTION, + /// The planner found an exact solution + EXACT_SOLUTION, + /// The planner crashed + CRASH, + /// The planner did not find a solution for some other reason + ABORT, + /// The planner decided that problem is infeasible + INFEASIBLE, + /// The number of possible status values + TYPE_COUNT + }; + + /// Default constructor + PlannerStatus(StatusType status = UNKNOWN) : status_(status) + { + } + + /// Convenience constructor that sets status_ based on whether some solution was found (\e hasSolution) and + /// whether that solution was approximate or not (\e isApproximate) + PlannerStatus(bool hasSolution, bool isApproximate) + : status_(hasSolution ? (isApproximate ? APPROXIMATE_SOLUTION : EXACT_SOLUTION) : TIMEOUT) + { + } + + /// Return a string representation + std::string asString() const; + /// Allow casting to true. The value is true iff an approximate or exact solution was found + operator bool() const + { + return status_ == APPROXIMATE_SOLUTION || status_ == EXACT_SOLUTION; + } + /// Allow casting to the enum type StatusType + operator StatusType() const + { + return status_; + } + + private: + /// Exit status of calling Planner::solve() + StatusType status_; + }; + + /// Print a PlannerStatus object + inline std::ostream &operator<<(std::ostream &out, const PlannerStatus &status) + { + return out << status.asString(); + } + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h new file mode 100644 index 00000000..58e0abed --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h @@ -0,0 +1,136 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_PLANNER_TERMINATION_CONDITION_ +#define OMPL_BASE_PLANNER_TERMINATION_CONDITION_ + +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief Signature for functions that decide whether termination + conditions have been met for a planner, even if no + solution is found. This is usually reaching a time or + memory limit. If the function returns true, the planner is + signaled to terminate its computation. Otherwise, + computation continues while this function returns false, + until a solution is found. */ + using PlannerTerminationConditionFn = std::function; + /** \brief Encapsulate a termination condition for a motion + planner. Planners will call operator() to decide whether + they should terminate before a solution is found or + not. operator() will return true if either the implemented + condition is met (the call to eval() returns true) or if + the user called terminate(true). */ + class PlannerTerminationCondition + { + public: + /** \brief Construct a termination condition. By default, eval() will call the externally specified function + \e fn to decide whether + the planner should terminate. */ + PlannerTerminationCondition(const PlannerTerminationConditionFn &fn); + + /** \brief Construct a termination condition that is evaluated every \e period seconds. The evaluation of + the condition consists of calling \e fn() in a separate thread. Calls to eval() will always return the + last value computed by the call to \e fn(). */ + PlannerTerminationCondition(const PlannerTerminationConditionFn &fn, double period); + + ~PlannerTerminationCondition() = default; + + /** \brief Return true if the planner should stop its computation */ + bool operator()() const + { + return eval(); + } + + /** \brief Cast as true if the planner should stop its computation */ + operator bool() const + { + return eval(); + } + + /** \brief Notify that the condition for termination should become true, regardless of what eval() returns. + This function may be called while the condition is being evaluated by other threads. */ + void terminate() const; + + /** \brief The implementation of some termination condition. By default, this just calls \e fn_() */ + bool eval() const; + + private: + class PlannerTerminationConditionImpl; + std::shared_ptr impl_; + }; + + /** \brief Simple termination condition that always returns false. The termination condition will never be met + */ + PlannerTerminationCondition plannerNonTerminatingCondition(); + + /** \brief Simple termination condition that always returns true. The termination condition will always be met + */ + PlannerTerminationCondition plannerAlwaysTerminatingCondition(); + + /** \brief Combine two termination conditions into one. If either termination condition returns true, this one + * will return true as well. */ + PlannerTerminationCondition plannerOrTerminationCondition(const PlannerTerminationCondition &c1, + const PlannerTerminationCondition &c2); + + /** \brief Combine two termination conditions into one. Both termination conditions need to return true for this + * one to return true. */ + PlannerTerminationCondition plannerAndTerminationCondition(const PlannerTerminationCondition &c1, + const PlannerTerminationCondition &c2); + + /** \brief Return a termination condition that will become true \e duration seconds in the future (wall-time) */ + PlannerTerminationCondition timedPlannerTerminationCondition(double duration); + + /** \brief Return a termination condition that will become true \e duration in the future (wall-time) */ + PlannerTerminationCondition timedPlannerTerminationCondition(time::duration duration); + + /** \brief Return a termination condition that will become true \e duration seconds in the future (wall-time), + * but is checked in a separate thread, every \e interval seconds; \e interval must be less than \e duration */ + PlannerTerminationCondition timedPlannerTerminationCondition(double duration, double interval); + + /** \brief Return a termination condition that will become true as soon as the problem definition has an exact + * solution */ + PlannerTerminationCondition exactSolnPlannerTerminationCondition(const ompl::base::ProblemDefinitionPtr &pdef); + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h new file mode 100644 index 00000000..803923f6 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h @@ -0,0 +1,72 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#include "ompl/base/StateSampler.h" +#include + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for discrete states */ + class PrecomputedStateSampler : public StateSampler + { + public: + /** \brief Constructor. Takes the state space to be sampled (\e space) and the set of states to draw samples + * from (\e states) */ + PrecomputedStateSampler(const StateSpace *space, const std::vector &states); + + /** \brief Constructor. Takes the state space to be sampled (\e space), the set of states to draw samples + * from (\e states) and a range to sample from: [\e minIndex, \e maxIndex]*/ + PrecomputedStateSampler(const StateSpace *space, const std::vector &states, + std::size_t minStateIndex, std::size_t maxStateIndex); + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + protected: + /** \brief The states to sample from */ + const std::vector &states_; + + /** \brief The minimum index to start sampling at */ + std::size_t minStateIndex_; + + /** \brief The maximum index to stop sampling at */ + std::size_t maxStateIndex_; + }; + } // namespace base +} // namespace ompl diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h new file mode 100644 index 00000000..62a96f26 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h @@ -0,0 +1,439 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_PROBLEM_DEFINITION_ +#define OMPL_BASE_PROBLEM_DEFINITION_ + +#include "ompl/base/State.h" +#include "ompl/base/Goal.h" +#include "ompl/base/Path.h" +#include "ompl/base/Cost.h" +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/SolutionNonExistenceProof.h" +#include "ompl/util/Console.h" +#include "ompl/util/ClassForward.h" +#include "ompl/base/ScopedState.h" + +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ProblemDefinition */ + OMPL_CLASS_FORWARD(ProblemDefinition); + OMPL_CLASS_FORWARD(OptimizationObjective); + /// @endcond + + /** \class ompl::base::ProblemDefinitionPtr + \brief A shared pointer wrapper for ompl::base::ProblemDefinition */ + + /** \brief Representation of a solution to a planning problem */ + struct PlannerSolution + { + /** \brief Construct a solution that consists of a \e path and its attributes (whether it is \e approximate + * and the \e difference to the desired goal) */ + PlannerSolution(const PathPtr &path) + : path_(path), length_(path ? path->length() : std::numeric_limits::infinity()) + { + } + + /** \brief Return true if two solutions are the same */ + bool operator==(const PlannerSolution &p) const + { + return path_ == p.path_; + } + + /** \brief Define a ranking for solutions */ + bool operator<(const PlannerSolution &b) const; + + /** \brief Specify that the solution is approximate and set the difference to the goal. */ + void setApproximate(double difference) + { + approximate_ = true; + difference_ = difference; + } + + /** \brief Set the optimization objective used to optimize this solution, the cost of the solution and + * whether it was optimized or not. */ + void setOptimized(const OptimizationObjectivePtr &opt, Cost cost, bool meetsObjective) + { + opt_ = opt; + cost_ = cost; + optimized_ = meetsObjective; + } + + /** \brief Set the name of the planner used to compute this solution */ + void setPlannerName(const std::string &name) + { + plannerName_ = name; + } + + /** \brief When multiple solutions are found, each is given a number starting at 0, so that the order in + * which the solutions was found can be retrieved. */ + int index_{-1}; + + /** \brief Solution path */ + PathPtr path_; + + /** \brief For efficiency reasons, keep the length of the path as well */ + double length_; + + /** \brief True if goal was not achieved, but an approximate solution was found */ + bool approximate_{false}; + + /** \brief The achieved difference between the found solution and the desired goal */ + double difference_{0.}; + + /** \brief True if the solution was optimized to meet the specified optimization criterion */ + bool optimized_{false}; + + /** \brief Optimization objective that was used to optimize this solution */ + OptimizationObjectivePtr opt_; + + /** \brief The cost of this solution path, with respect to the optimization objective */ + Cost cost_; + + /** \brief Name of planner type that generated this solution, as received from Planner::getName() */ + std::string plannerName_; + }; + + class Planner; + + /** \brief When a planner has an intermediate solution (e.g., optimizing planners), a function with this + signature can be called + to report the states of that solution. */ + using ReportIntermediateSolutionFn = + std::function &, const Cost)>; + + OMPL_CLASS_FORWARD(OptimizationObjective); + + /** \brief Definition of a problem to be solved. This includes + the start state(s) for the system and a goal specification. + Will contain solutions, if found. */ + class ProblemDefinition + { + public: + // non-copyable + ProblemDefinition(const ProblemDefinition &) = delete; + ProblemDefinition &operator=(const ProblemDefinition &) = delete; + + /** \brief Create a problem definition given the SpaceInformation it is part of */ + ProblemDefinition(SpaceInformationPtr si); + + /** \brief Return a copy of the problem definition + * + * A deep copy is made of the start and goal states. A shallow copy is made + * of shared ptrs. The set of solutions paths and the intermediate solution + * callback function are not copied. + */ + ProblemDefinitionPtr clone() const; + + virtual ~ProblemDefinition() + { + clearStartStates(); + } + + /** \brief Get the space information this problem definition is for */ + const SpaceInformationPtr &getSpaceInformation() const + { + return si_; + } + + /** \brief Add a start state. The state is copied. */ + void addStartState(const State *state) + { + startStates_.push_back(si_->cloneState(state)); + } + + /** \copydoc addStartState() */ + void addStartState(const ScopedState<> &state) + { + startStates_.push_back(si_->cloneState(state.get())); + } + + /** \brief Check whether a specified starting state is + already included in the problem definition and + optionally return the index of that starting state */ + bool hasStartState(const State *state, unsigned int *startIndex = nullptr) const; + + /** \brief Clear all start states (memory is freed) */ + void clearStartStates() + { + for (auto &startState : startStates_) + si_->freeState(startState); + startStates_.clear(); + } + + /** \brief Returns the number of start states */ + unsigned int getStartStateCount() const + { + return startStates_.size(); + } + + /** \brief Returns a specific start state */ + const State *getStartState(unsigned int index) const + { + return startStates_[index]; + } + + /** \copydoc getStartState() */ + State *getStartState(unsigned int index) + { + return startStates_[index]; + } + + /** \brief Set the goal. */ + void setGoal(const GoalPtr &goal) + { + goal_ = goal; + } + + /** \brief Clear the goal. Memory is freed. */ + void clearGoal() + { + goal_.reset(); + } + + /** \brief Return the current goal */ + const GoalPtr &getGoal() const + { + return goal_; + } + + /** \brief Get all the input states. This includes start + states and states that are part of goal regions that + can be casted as ompl::base::GoalState or + ompl::base::GoalStates. */ + void getInputStates(std::vector &states) const; + + /** \brief In the simplest case possible, we have a single + starting state and a single goal state. + + This function simply configures the problem definition + using these states (performs the needed calls to + addStartState(), creates an instance of + ompl::base::GoalState and calls setGoal() on it. */ + void setStartAndGoalStates(const State *start, const State *goal, + double threshold = std::numeric_limits::epsilon()); + + /** \brief A simple form of setting the goal. This is called by setStartAndGoalStates(). A more general form + * is setGoal() */ + void setGoalState(const State *goal, double threshold = std::numeric_limits::epsilon()); + + /** \copydoc setStartAndGoalStates() */ + void setStartAndGoalStates(const ScopedState<> &start, const ScopedState<> &goal, + const double threshold = std::numeric_limits::epsilon()) + { + setStartAndGoalStates(start.get(), goal.get(), threshold); + } + + /** \copydoc setGoalState() */ + void setGoalState(const ScopedState<> &goal, + const double threshold = std::numeric_limits::epsilon()) + { + setGoalState(goal.get(), threshold); + } + + /** \brief Check if an optimization objective was defined for planning */ + bool hasOptimizationObjective() const + { + return optimizationObjective_ != nullptr; + } + + /** \brief Get the optimization objective to be considered during planning */ + const OptimizationObjectivePtr &getOptimizationObjective() const + { + return optimizationObjective_; + } + + /** \brief Set the optimization objective to be considered during planning */ + void setOptimizationObjective(const OptimizationObjectivePtr &optimizationObjective) + { + optimizationObjective_ = optimizationObjective; + } + + /** \brief When this function returns a valid function pointer, that function should be called + by planners that compute intermediate solutions every time a better solution is found */ + const ReportIntermediateSolutionFn &getIntermediateSolutionCallback() const + { + return intermediateSolutionCallback_; + } + + /** \brief Set the callback to be called by planners that can compute intermediate solutions */ + void setIntermediateSolutionCallback(const ReportIntermediateSolutionFn &callback) + { + intermediateSolutionCallback_ = callback; + } + + /** \brief A problem is trivial if a given starting state already + in the goal region, so we need no motion planning. startID + will be set to the index of the starting state that + satisfies the goal. The distance to the goal can + optionally be returned as well. */ + bool isTrivial(unsigned int *startIndex = nullptr, double *distance = nullptr) const; + + /** \brief Check if a straight line path is valid. If it + is, return an instance of a path that represents the + straight line. + + \note When planning under geometric constraints, this + works only if the goal region can be sampled. If the + goal region cannot be sampled, this call is equivalent + to calling isTrivial() + + \note When planning under differential constraints, + the system is propagated forward in time using the + null control. */ + PathPtr isStraightLinePathValid() const; + + /** \brief Many times the start or goal state will barely touch an obstacle. In this case, we may want to + * automatically + * find a nearby state that is valid so motion planning can be performed. This function enables this + * behaviour. + * The allowed distance for both start and goal states is specified. The number of attempts + * is also specified. Returns true if all states are valid after completion. */ + bool fixInvalidInputStates(double distStart, double distGoal, unsigned int attempts); + + /** \brief Returns true if a solution path has been found (could be approximate) */ + bool hasSolution() const; + + /** \brief Returns true if an exact solution path has been found. Specifically returns hasSolution && + * !hasApproximateSolution() */ + bool hasExactSolution() const + { + return this->hasSolution() && !this->hasApproximateSolution(); + } + + /** \brief Return true if the top found solution is + approximate (does not actually reach the desired goal, + but hopefully is closer to it) */ + bool hasApproximateSolution() const; + + /** \brief Get the distance to the desired goal for the top solution. Return -1.0 if there are no solutions + * available. */ + double getSolutionDifference() const; + + /** \brief Return true if the top found solution is optimized (satisfies the specified optimization + * objective) */ + bool hasOptimizedSolution() const; + + /** \brief Return the top solution path, if one is found. The top path is a shortest + path that was found, preference being given to solutions that are not approximate. + + This will need to be casted into the specialization computed by the planner */ + PathPtr getSolutionPath() const; + + /** \brief Return true if a top solution is found, with the top solution passed by reference in the function + header + The top path is a shortest path that was found, preference being given to solutions that are not + approximate. + This will need to be casted into the specialization computed by the planner */ + bool getSolution(PlannerSolution &solution) const; + + /** \brief Add a solution path in a thread-safe manner. Multiple solutions can be set for a goal. + If a solution does not reach the desired goal it is considered approximate. + Optionally, the distance between the desired goal and the one actually achieved is set by \e difference. + Optionally, the name of the planner that generated the solution + */ + void addSolutionPath(const PathPtr &path, bool approximate = false, double difference = -1.0, + const std::string &plannerName = "Unknown") const; + + /** \brief Add a solution path in a thread-safe manner. Multiple solutions can be set for a goal. */ + void addSolutionPath(const PlannerSolution &sol) const; + + /** \brief Get the number of solutions already found */ + std::size_t getSolutionCount() const; + + /** \brief Get all the solution paths available for this goal */ + std::vector getSolutions() const; + + /** \brief Forget the solution paths (thread safe). Memory is freed. */ + void clearSolutionPaths() const; + + /** \brief Returns true if the problem definition has a proof of non existence for a solution */ + bool hasSolutionNonExistenceProof() const; + + /** \brief Removes any existing instance of SolutionNonExistenceProof */ + void clearSolutionNonExistenceProof(); + + /** \brief Retrieve a pointer to the SolutionNonExistenceProof instance for this problem definition */ + const SolutionNonExistenceProofPtr &getSolutionNonExistenceProof() const; + + /** \brief Set the instance of SolutionNonExistenceProof for this problem definition */ + void setSolutionNonExistenceProof(const SolutionNonExistenceProofPtr &nonExistenceProof); + + /** \brief Print information about the start and goal states and the optimization objective */ + void print(std::ostream &out = std::cout) const; + + protected: + /** \brief Helper function for fixInvalidInputStates(). Attempts to fix an individual state */ + bool fixInvalidInputState(State *state, double dist, bool start, unsigned int attempts); + + /** \brief The space information this problem definition is for */ + SpaceInformationPtr si_; + + /** \brief The set of start states */ + std::vector startStates_; + + /** \brief The goal representation */ + GoalPtr goal_; + + /** \brief A Representation of a proof of non-existence of a solution for this problem definition */ + SolutionNonExistenceProofPtr nonExistenceProof_; + + /** \brief The objective to be optimized while solving the planning problem */ + OptimizationObjectivePtr optimizationObjective_; + + /** \brief Callback function which is called when a new intermediate solution has been found.*/ + ReportIntermediateSolutionFn intermediateSolutionCallback_; + + private: + /// @cond IGNORE + OMPL_CLASS_FORWARD(PlannerSolutionSet); + /// @endcond + + /** \brief The set of solutions computed for this goal (maintains an array of PlannerSolution) */ + PlannerSolutionSetPtr solutions_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h new file mode 100644 index 00000000..e46739f3 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h @@ -0,0 +1,334 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_PROJECTION_EVALUATOR_ +#define OMPL_BASE_PROJECTION_EVALUATOR_ + +#include "ompl/base/State.h" +#include "ompl/util/ClassForward.h" +#include "ompl/util/Console.h" +#include "ompl/base/GenericParam.h" +#include "ompl/base/spaces/RealVectorBounds.h" + +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief A projection matrix -- it allows multiplication of + real vectors by a specified matrix. The matrix can also be + randomly generated. */ + class ProjectionMatrix + { + public: + /** \brief Datatype for projection matrices */ + using Matrix = Eigen::MatrixXd; + + /** \brief Compute a random projection matrix with \e from + columns and \e to rows. A vector with \e from elements + can be multiplied by this matrix in order to produce a + vector with \e to elements. + + If the \e scale argument is specified, the columns of + the matrix are divided by the corresponding scaling + argument: all elements (rows) in column[i] are divided + by scale[i]. This is useful to specify if scaling of + the elements of the state is to be applied before + projection. If the scale for a column is 0, the column + itself is set to 0. + + Each element is sampled with a Gaussian distribution + with mean 0 and variance 1 and the matrix rows are + made orthonormal. */ + static Matrix ComputeRandom(unsigned int from, unsigned int to, const std::vector &scale); + + /** \brief Compute a random projection matrix with \e from + columns and \e to rows. A vector with \e from elements + can be multiplied by this matrix in order to produce a + vector with \e to elements. This uses the function above + called with an empty \e scale vector. + + Each element is sampled with a Gaussian distribution + with mean 0 and variance 1 and the matrix rows are + made orthonormal. */ + static Matrix ComputeRandom(unsigned int from, unsigned int to); + + /** \brief Wrapper for ComputeRandom(from, to, scale) */ + void computeRandom(unsigned int from, unsigned int to, const std::vector &scale); + + /** \brief Wrapper for ComputeRandom(from, to) */ + void computeRandom(unsigned int from, unsigned int to); + + /** \brief Multiply the vector \e from by the contained projection matrix to obtain the vector \e to. */ + void project(const double *from, Eigen::Ref to) const; + + /** \brief Print the contained projection matrix to a stram */ + void print(std::ostream &out = std::cout) const; + + /** \brief Projection matrix */ + Matrix mat; + + public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + }; + + /// @cond IGNORE + OMPL_CLASS_FORWARD(StateSpace); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ProjectionEvaluator */ + OMPL_CLASS_FORWARD(ProjectionEvaluator); + /// @endcond + + /** \class ompl::base::ProjectionEvaluatorPtr + \brief A shared pointer wrapper for ompl::base::ProjectionEvaluator */ + + /** \brief Abstract definition for a class computing + projections to Rn. Implicit integer grids are + imposed on this projection space by setting cell + sizes. Before use, the user must supply cell sizes + for the integer grid (setCellSizes()). The + implementation of this class is thread safe. */ + class ProjectionEvaluator + { + public: + // non-copyable + ProjectionEvaluator(const ProjectionEvaluator &) = delete; + ProjectionEvaluator &operator=(const ProjectionEvaluator &) = delete; + + /** \brief Construct a projection evaluator for a specific state space */ + ProjectionEvaluator(const StateSpace *space); + + /** \brief Construct a projection evaluator for a specific state space */ + ProjectionEvaluator(const StateSpacePtr &space); + + virtual ~ProjectionEvaluator(); + + /** \brief Return the dimension of the projection defined by this evaluator */ + virtual unsigned int getDimension() const = 0; + + /** \brief Compute the projection as an array of double values */ + virtual void project(const State *state, Eigen::Ref projection) const = 0; + + /** \brief Define the size (in each dimension) of a grid + cell. The number of sizes set here must be the + same as the dimension of the projection computed by + the projection evaluator. After a call to this + function, setup() will not call + defaultCellSizes() or inferCellSizes() any + more. */ + virtual void setCellSizes(const std::vector &cellSizes); + + /** \brief Set the cell sizes to \e cellSize for a particular dimension \e dim. This function simply calls + getCellSizes(), + modifies the desired dimension and then calls setCellSizes(). This is done intentionally to enforce a + call to setCellSizes(). */ + void setCellSizes(unsigned int dim, double cellSize); + + /** \brief Multiply the cell sizes in each dimension by a specified factor \e factor. This function does + nothing + if cell sizes have not been set. If cell sizes have been set (irrespective of source; e.g., user, + default or inferred), + this function will then call setCellSizes(), so the source of the cell sizes will be considered to be + the user. */ + void mulCellSizes(double factor); + + /** \brief Return true if any user configuration has been done to this projection evaluator (setCellSizes() + * was called) */ + bool userConfigured() const; + + /** \brief Get the size (each dimension) of a grid cell */ + const std::vector &getCellSizes() const + { + return cellSizes_; + } + + /** \brief Get the size of a particular dimension of a grid cell */ + double getCellSizes(unsigned int dim) const; + + /** \brief Check if cell dimensions match projection dimension */ + void checkCellSizes() const; + + /** \brief Sample the state space and decide on default + cell sizes. This function is called by setup() if + no cell dsizes have been set and + defaultCellSizes() does not fill the cell + sizes either. */ + void inferCellSizes(); + + /** \brief Set the default cell dimensions for this + projection. The default implementation of this + function is empty. setup() calls this function if no + cell dimensions have been previously set. */ + virtual void defaultCellSizes(); + + /** \brief Check if the projection dimension matched the dimension of the bounds */ + void checkBounds() const; + + /** \brief Check if bounds were specified for this projection */ + bool hasBounds() const + { + return !bounds_.low.empty(); + } + + /** \brief Set bounds on the projection. The PDST planner + needs to known the bounds on the projection. Default bounds + are automatically computed by inferCellSizes(). */ + void setBounds(const RealVectorBounds &bounds); + + /** \brief Get the bounds computed/set for this projection */ + const RealVectorBounds &getBounds() const + { + return bounds_; + } + + /** \brief Compute an approximation of the bounds for this projection space. getBounds() will then report + * the computed bounds. */ + void inferBounds(); + + /** \brief Perform configuration steps, if needed */ + virtual void setup(); + + /** \brief Compute integer coordinates for a projection */ + void computeCoordinates(const Eigen::Ref &projection, + Eigen::Ref coord) const; + + /** \brief Compute integer coordinates for a state */ + void computeCoordinates(const State *state, Eigen::Ref coord) const + { + Eigen::VectorXd projection(getDimension()); + project(state, projection); + computeCoordinates(projection, coord); + } + + /** \brief Get the parameters for this projection */ + ParamSet ¶ms() + { + return params_; + } + + /** \brief Get the parameters for this projection */ + const ParamSet ¶ms() const + { + return params_; + } + + /** \brief Print settings about this projection */ + virtual void printSettings(std::ostream &out = std::cout) const; + + /** \brief Print a euclidean projection */ + virtual void printProjection(const Eigen::Ref &projection, + std::ostream &out = std::cout) const; + + protected: + /** \brief Fill estimatedBounds_ with an approximate bounding box for the projection space (via sampling) */ + void estimateBounds(); + + /** \brief The state space this projection operates on */ + const StateSpace *space_; + + /** \brief The size of a cell, in every dimension of the + projected space, in the implicitly defined integer + grid. */ + std::vector cellSizes_; + + /** \brief A bounding box for projected state values */ + RealVectorBounds bounds_; + + /** \brief An approximate bounding box for projected state values; + This is the cached result of estimateBounds() which may later be copied + to bounds_ if bounds are needed but were not specified. */ + RealVectorBounds estimatedBounds_; + + /** \brief Flag indicating whether cell sizes have + been set by the user, or whether they were inferred + automatically. This flag becomes false if + setCellSizes() is called. */ + bool defaultCellSizes_; + + /** \brief Flag indicating whether projection cell sizes + were automatically inferred. */ + bool cellSizesWereInferred_; + + /** \brief The set of parameters for this projection */ + ParamSet params_; + }; + + /** \brief If the projection for a CompoundStateSpace is + supposed to be the same as the one for one of its included + subspaces, this class facilitates selecting a projection + of that subspace. */ + class SubspaceProjectionEvaluator : public ProjectionEvaluator + { + public: + /** \brief The constructor states that for space \e space, + the projection to use is the same as the component at + position \e index of space \e space. The actual + projection to use can be specified by \e projToUse. If + the projection is not specified, the default one for + the subspace at position \e index is used. */ + SubspaceProjectionEvaluator(const StateSpace *space, unsigned int index, + ProjectionEvaluatorPtr projToUse = ProjectionEvaluatorPtr()); + + void setup() override; + + unsigned int getDimension() const override; + + void project(const State *state, Eigen::Ref projection) const override; + + protected: + /** \brief The index of the subspace from which to project */ + unsigned int index_; + + /** \brief The projection to use. This is either the same + as \e specifiedProj_ or, if specifiedProj_ is not + initialized, it is the default projection for the + subspace at index \e index_ */ + ProjectionEvaluatorPtr proj_; + + /** \brief The projection that is optionally specified by the user in the constructor argument (\e + * projToUse) */ + ProjectionEvaluatorPtr specifiedProj_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h new file mode 100644 index 00000000..07fc6140 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h @@ -0,0 +1,553 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SCOPED_STATE_ +#define OMPL_BASE_SCOPED_STATE_ + +#include "ompl/base/SpaceInformation.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief Definition of a scoped state. + + This class allocates a state of a desired type using the + allocation mechanism of the corresponding state space. + The state is then freed when the instance goes out of + scope using the corresponding free mechanism. */ + template + class ScopedState + { + /** \brief Make sure the type we are allocating is indeed from a state space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + public: + /** \brief The type of the contained state */ + using StateType = typename T::StateType; + + /** \brief Given the space that we are working with, + allocate a state from the corresponding + state space. */ + explicit ScopedState(const SpaceInformationPtr &si) : space_(si->getStateSpace()) + { + State *s = space_->allocState(); + + // ideally, this should be a dynamic_cast and we + // should throw an exception in case of + // failure. However, RTTI may not be available across + // shared library boundaries, so we do not use it + state_ = static_cast(s); + } + + /** \brief Given the state space that we are working with, + allocate a state. */ + explicit ScopedState(StateSpacePtr space) : space_(std::move(space)) + { + State *s = space_->allocState(); + + // ideally, this should be a dynamic_cast and we + // should throw an exception in case of + // failure. However, RTTI may not be available across + // shared library boundaries, so we do not use it + state_ = static_cast(s); + } + + /** \brief Copy constructor */ + ScopedState(const ScopedState &other) : space_(other.getSpace()) + { + State *s = space_->allocState(); + state_ = static_cast(s); + space_->copyState(s, static_cast(other.get())); + } + + /** \brief Copy constructor that allows instantiation from states of other type */ + template + ScopedState(const ScopedState &other) : space_(other.getSpace()) + { + BOOST_CONCEPT_ASSERT((boost::Convertible)); + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + // ideally, we should use a dynamic_cast and throw an + // exception in case other.get() does not cast to + // const StateType*. However, RTTI may not be + // available across shared library boundaries, so we + // do not use it + + State *s = space_->allocState(); + state_ = static_cast(s); + space_->copyState(s, static_cast(other.get())); + } + + /** \brief Given the state space that we are working with, + allocate a state and fill that state with a given value. */ + ScopedState(StateSpacePtr space, const State *state) : space_(std::move(space)) + { + State *s = space_->allocState(); + space_->copyState(s, state); + + // ideally, this should be a dynamic_cast and we + // should throw an exception in case of + // failure. However, RTTI may not be available across + // shared library boundaries, so we do not use it + state_ = static_cast(s); + } + + /** \brief Free the memory of the internally allocated state */ + ~ScopedState() + { + space_->freeState(state_); + } + + /** \brief Get the state space that the state corresponds to */ + const StateSpacePtr &getSpace() const + { + return space_; + } + + /** \brief Assignment operator */ + ScopedState &operator=(const ScopedState &other) + { + if (&other != this) + { + space_->freeState(state_); + space_ = other.getSpace(); + + State *s = space_->allocState(); + state_ = static_cast(s); + space_->copyState(s, static_cast(other.get())); + } + return *this; + } + + /** \brief Assignment operator */ + ScopedState &operator=(const State *other) + { + if (other != static_cast(state_)) + { + // ideally, we should use a dynamic_cast and throw an + // exception in case other does not cast to + // const StateType*. However, RTTI may not be + // available across shared library boundaries, so we + // do not use it + + space_->copyState(static_cast(state_), other); + } + return *this; + } + + /** \brief Assignment operator */ + ScopedState &operator=(const State &other) + { + if (&other != static_cast(state_)) + { + // ideally, we should use a dynamic_cast and throw an + // exception in case &other does not cast to + // const StateType*. However, RTTI may not be + // available across shared library boundaries, so we + // do not use it + + space_->copyState(static_cast(state_), &other); + } + return *this; + } + + /** \brief Assignment operator that allows conversion of states */ + template + ScopedState &operator=(const ScopedState &other) + { + BOOST_CONCEPT_ASSERT((boost::Convertible)); + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + // ideally, we should use a dynamic_cast and throw an + // exception in case other.get() does not cast to + // const StateType*. However, RTTI may not be + // available across shared library boundaries, so we + // do not use it + + if (reinterpret_cast(&other) != reinterpret_cast(this)) + { + space_->freeState(state_); + space_ = other.getSpace(); + + State *s = space_->allocState(); + state_ = static_cast(s); + space_->copyState(s, static_cast(other.get())); + } + return *this; + } + + /** \brief Partial assignment operator. Only sets the double values of the state to specified real values */ + ScopedState &operator=(const std::vector &reals) + { + for (unsigned int i = 0; i < reals.size(); ++i) + if (double *va = space_->getValueAddressAtIndex(state_, i)) + *va = reals[i]; + else + break; + return *this; + } + + /** \brief Partial assignment operator. Only sets the double values of the state to a fixed value */ + ScopedState &operator=(const double value) + { + unsigned int index = 0; + while (double *va = space_->getValueAddressAtIndex(state_, index++)) + *va = value; + return *this; + } + + /** \brief Checks equality of two states */ + template + bool operator==(const ScopedState &other) const + { + BOOST_CONCEPT_ASSERT((boost::Convertible)); + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + // ideally, we should use a dynamic_cast and throw an + // exception in case other.get() does not cast to + // const StateType*. However, RTTI may not be + // available across shared library boundaries, so we + // do not use it + + return space_->equalStates(static_cast(state_), static_cast(other.get())); + } + + /** \brief Checks equality of two states */ + template + bool operator!=(const ScopedState &other) const + { + return !(*this == other); + } + + /** \brief Extract a state that corresponds to the + components in state space \e s. Those components will + have the same value as the current state (only the + ones included in the current state; others will be + uninitialised). Note: a new state is constructed and data is copied. */ + const ScopedState<> operator[](const StateSpacePtr &s) const; + + /** \brief Access the \e indexth double value this state contains. */ + double &operator[](const unsigned int index) + { + double *val = space_->getValueAddressAtIndex(state_, index); + if (val == nullptr) + throw Exception("Index out of bounds"); + return *val; + } + + /** \brief Access the \e indexth double value this state contains. */ + double operator[](const unsigned int index) const + { + const double *val = space_->getValueAddressAtIndex(state_, index); + if (val == nullptr) + throw Exception("Index out of bounds"); + return *val; + } + + /** \brief Access a double value from this state contains using its name. */ + double &operator[](const std::string &name) + { + const std::map &vm = space_->getValueLocationsByName(); + auto it = vm.find(name); + if (it != vm.end()) + { + double *val = space_->getValueAddressAtLocation(state_, it->second); + if (val != nullptr) + return *val; + } + throw Exception("Name '" + name + "' not known"); + } + + /** \brief Access a double value from this state contains using its name. */ + double operator[](const std::string &name) const + { + const std::map &vm = space_->getValueLocationsByName(); + auto it = vm.find(name); + if (it != vm.end()) + { + const double *val = space_->getValueAddressAtLocation(state_, it->second); + if (val != nullptr) + return *val; + } + throw Exception("Name '" + name + "' not known"); + } + + /** \brief Compute the distance to another state. */ + template + double distance(const ScopedState &other) const + { + BOOST_CONCEPT_ASSERT((boost::Convertible)); + BOOST_CONCEPT_ASSERT((boost::Convertible)); + return distance(other.get()); + } + + /** \brief Compute the distance to another state. */ + double distance(const State *state) const + { + return space_->distance(static_cast(state_), state); + } + + /** \brief Set this state to a random value (uniform) */ + void random() + { + if (!sampler_) + sampler_ = space_->allocStateSampler(); + sampler_->sampleUniform(state_); + } + + /** \brief Enforce the bounds on the maintained state */ + void enforceBounds() + { + space_->enforceBounds(state_); + } + + /** \brief Check if the maintained state satisfies bounds */ + bool satisfiesBounds() const + { + return space_->satisfiesBounds(state_); + } + + /** \brief Return the real values corresponding to this + state. If a conversion is not possible, an exception + is thrown.*/ + std::vector reals() const + { + std::vector r; + unsigned int index = 0; + while (double *va = space_->getValueAddressAtIndex(state_, index++)) + r.push_back(*va); + return r; + } + + /** \brief Print this state to a stream */ + void print(std::ostream &out = std::cout) const + { + space_->printState(state_, out); + } + + /** \brief De-references to the contained state */ + StateType &operator*() + { + return *state_; + } + + /** \brief De-references to the contained state */ + const StateType &operator*() const + { + return *state_; + } + + /** \brief Returns a pointer to the contained state */ + StateType *operator->() + { + return state_; + } + + /** \brief Returns a pointer to the contained state */ + const StateType *operator->() const + { + return state_; + } + + /** \brief Returns a pointer to the contained state */ + StateType *get() + { + return state_; + } + + /** \brief Returns a pointer to the contained state */ + const StateType *get() const + { + return state_; + } + + /** \brief Returns a pointer to the contained state (used for Python bindings) */ + StateType *operator()() const + { + return state_; + } + + private: + StateSpacePtr space_; + StateSamplerPtr sampler_; + StateType *state_; + }; + + /** \addtogroup stateAndSpaceOperators Operators for States and State Spaces + + These operators are intended to simplify code that + manipulates states and state spaces. They rely on the fact + that state spaces have unique names. Here are some examples + for using these operators: + \code{.cpp} + // Assume X, Y, Z, W are state space instances, none of + // which inherits from ompl::base::CompoundStateSpace. + // Denote a compound state space as C[...], where "..." is the + // list of subspaces. + + ompl::base::StateSpacePtr X; + ompl::base::StateSpacePtr Y; + ompl::base::StateSpacePtr Z; + ompl::base::StateSpacePtr W; + + // the following line will construct a state space C1 = C[X, Y] + ompl::base::StateSpacePtr C1 = X + Y; + + // the following line will construct a state space C2 = C[X, Y, Z] + ompl::base::StateSpacePtr C2 = C1 + Z; + + // the following line will leave C2 as C[X, Y, Z] + ompl::base::StateSpacePtr C2 = C1 + C2; + + // the following line will construct a state space C2 = C[X, Y, Z, W] + ompl::base::StateSpacePtr C2 = C2 + W; + + // the following line will construct a state space C3 = C[X, Z, Y] + ompl::base::StateSpacePtr C3 = X + Z + Y; + + // the following line will construct a state space C4 = C[Z, W] + ompl::base::StateSpacePtr C4 = C2 - C1; + + // the following line will construct a state space C5 = W + ompl::base::StateSpacePtr C5 = C2 - C3; + + // the following line will construct an empty state space C6 = C[] + ompl::base::StateSpacePtr C6 = X - X; + + // the following line will construct a state space C7 = Y + ompl::base::StateSpacePtr C7 = Y + C6; + \endcode + These state spaces can be used when operating with states: + \code{.cpp} + ompl::base::ScopedState<> sX(X); + ompl::base::ScopedState<> sXY(X + Y); + ompl::base::ScopedState<> sY(Y); + ompl::base::ScopedState<> sZX(Z + X); + ompl::base::ScopedState<> sXZW(X + Z + W); + + // the following line will copy the content of the state sX to + // the corresponding locations in sXZW. The components of the state + // corresponding to the Z and W state spaces are not touched + sX >> sXZW; + + // the following line will initialize the X component of sXY with + // the X component of sXZW; + sXY << sXZW; + + // the following line will initialize both components of sZX, using + // the X and Z components of sXZW; + sZX << sXZW; + + // the following line compares the concatenation of states sX and sY with sXY + // the concatenation will automatically construct the state space X + Y and a state + // from that state space containing the information from sX and sY. Since sXY is + // constructed from the state space X + Y, the two are comparable. + bool eq = (sX ^ sY) == sXY; + \endcode + @{ + */ + + /** \brief Overload stream output operator. Calls ompl::base::StateSpace::printState() */ + template + inline std::ostream &operator<<(std::ostream &out, const ScopedState &state) + { + state.print(out); + return out; + } + + /** \brief This is a fancy version of the assignment + operator. It is a partial assignment, in some sense. The + difference is that if the states are part of compound + state spaces, the data is copied from \e from to \e to on a + component by component basis. State spaces are matched by + name. If the state space for \e to contains any subspace + whose name matches any subspace of the state space for \e + from, the corresponding state components are copied. */ + template + inline ScopedState &operator<<(ScopedState &to, const ScopedState &from) + { + copyStateData(to.getSpace(), to.get(), from.getSpace(), from.get()); + return to; + } + + /** \brief This is a fancy version of the assignment + operator. It is a partial assignment, in some sense. The + difference is that if the states are part of compound + state spaces, the data is copied from \e from to \e to on a + component by component basis. State spaces are matched by + name. If the state space for \e to contains any subspace + whose name matches any subspace of the state space for \e + from, the corresponding state components are copied. */ + template + inline const ScopedState &operator>>(const ScopedState &from, ScopedState &to) + { + copyStateData(to.getSpace(), to.get(), from.getSpace(), from.get()); + return from; + } + + /** \brief Given state \e a from state space A and state \e b + from state space B, construct a state from state space A + + B. The resulting state contains all the information from + the input states (the states are concatenated). */ + template + inline const ScopedState<> operator^(const ScopedState &a, const ScopedState &b) + { + ScopedState<> r(a.getSpace() + b.getSpace()); + return r << a << b; + } + + /** @} */ + + template + const ScopedState<> ScopedState::operator[](const StateSpacePtr &s) const + { + ScopedState<> r(s); + return r << *this; + } + + /** \brief Shared pointer to a ScopedState<> */ + using ScopedStatePtr = std::shared_ptr>; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h new file mode 100644 index 00000000..717f2dc6 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h @@ -0,0 +1,73 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_BASE_SOLUTION_NON_EXISTENCE_PROOF_ +#define OMPL_BASE_SOLUTION_NON_EXISTENCE_PROOF_ + +#include + +#include "ompl/base/SpaceInformation.h" +#include "ompl/util/ClassForward.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /// \brief Forward declaration of ompl::base::SolutionNonExistenceProof + OMPL_CLASS_FORWARD(SolutionNonExistenceProof); + /// @endcond + + /// \class ompl::base::SolutionNonExistenceProofPtr + /// \brief A shared pointer wrapper for ompl::base::SolutionNonExistenceProof + + /// \brief Abstract definition of a proof for the non-existence of a solution to a problem + class SolutionNonExistenceProof + { + public: + SolutionNonExistenceProof(SpaceInformationPtr si) : si_(std::move(si)) + { + } + + virtual ~SolutionNonExistenceProof() = default; + + protected: + SpaceInformationPtr si_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h new file mode 100644 index 00000000..16f975a2 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h @@ -0,0 +1,459 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACE_INFORMATION_ +#define OMPL_BASE_SPACE_INFORMATION_ + +#include "ompl/base/State.h" +#include "ompl/base/StateValidityChecker.h" +#include "ompl/base/MotionValidator.h" +#include "ompl/base/StateSpace.h" +#include "ompl/base/ValidStateSampler.h" + +#include "ompl/util/ClassForward.h" +#include "ompl/util/Console.h" +#include "ompl/util/Exception.h" + +#include +#include +#include +#include +#include + +/** \brief Main namespace. Contains everything in this library */ +namespace ompl +{ + /** \brief This namespace contains sampling based planning + routines shared by both planning under geometric constraints + (geometric) and planning under differential constraints + (dynamic) */ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::SpaceInformation */ + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /** \class ompl::base::SpaceInformationPtr + \brief A shared pointer wrapper for ompl::base::SpaceInformation */ + + /** \brief If no state validity checking class is specified + (StateValidityChecker), a std::function can be specified + instead */ + using StateValidityCheckerFn = std::function; + + /** \brief The base class for space information. This contains + all the information about the space planning is done in. + setup() needs to be called as well, before use */ + class SpaceInformation + { + public: + // non-copyable + SpaceInformation(const SpaceInformation &) = delete; + SpaceInformation &operator=(const SpaceInformation &) = delete; + + /** \brief Constructor. Sets the instance of the state space to plan with. */ + SpaceInformation(StateSpacePtr space); + + virtual ~SpaceInformation() = default; + + /** \brief Check if a given state is valid or not */ + bool isValid(const State *state) const + { + return stateValidityChecker_->isValid(state); + } + + /** \brief Return the instance of the used state space */ + const StateSpacePtr &getStateSpace() const + { + return stateSpace_; + } + + /** @name Topology-specific state operations (as in the state space) + @{ */ + + /** \brief Check if two states are the same */ + bool equalStates(const State *state1, const State *state2) const + { + return stateSpace_->equalStates(state1, state2); + } + + /** \brief Check if a state is inside the bounding box */ + bool satisfiesBounds(const State *state) const + { + return stateSpace_->satisfiesBounds(state); + } + + /** \brief Compute the distance between two states */ + double distance(const State *state1, const State *state2) const + { + return stateSpace_->distance(state1, state2); + } + + /** \brief Bring the state within the bounds of the state space */ + void enforceBounds(State *state) const + { + stateSpace_->enforceBounds(state); + } + + /** \brief Print a state to a stream */ + void printState(const State *state, std::ostream &out = std::cout) const + { + stateSpace_->printState(state, out); + } + + /** @} */ + + /** @name Configuration of state validity checking + @{ */ + + /** \brief Set the instance of the state validity checker + to use. Parallel implementations of planners assume + this validity checker is thread safe. */ + void setStateValidityChecker(const StateValidityCheckerPtr &svc) + { + stateValidityChecker_ = svc; + setup_ = false; + } + + /** \brief If no state validity checking class is + specified (StateValidityChecker), a function can + be specified instead. This version however incurs a + small additional overhead when calling the function, + since there is one more level of indirection */ + void setStateValidityChecker(const StateValidityCheckerFn &svc); + + /** \brief Return the instance of the used state validity checker */ + const StateValidityCheckerPtr &getStateValidityChecker() const + { + return stateValidityChecker_; + } + + /** \brief Set the instance of the motion validity checker + to use. Parallel implementations of planners assume + this validity checker is thread safe. */ + void setMotionValidator(const MotionValidatorPtr &mv) + { + motionValidator_ = mv; + setup_ = false; + } + + /** \brief Return the instance of the used state validity checker */ + const MotionValidatorPtr &getMotionValidator() const + { + return motionValidator_; + } + + /** \brief Return the non-const instance of the used state validity checker */ + MotionValidatorPtr &getMotionValidator() + { + return motionValidator_; + } + + /** \brief Set the resolution at which state validity + needs to be verified in order for a motion between two + states to be considered valid. This value is specified + as a fraction of the space's extent. This call is only + applicable if a ompl::base::DiscreteMotionValidator is + used. See \ref stateValidation. */ + void setStateValidityCheckingResolution(double resolution) + { + stateSpace_->setLongestValidSegmentFraction(resolution); + setup_ = false; + } + + /** \brief Get the resolution at which state validity is + verified. This call is only applicable if a + ompl::base::DiscreteMotionValidator is used. See \ref + stateValidation. */ + double getStateValidityCheckingResolution() const + { + return stateSpace_->getLongestValidSegmentFraction(); + } + + /** @}*/ + + /** \brief Return the dimension of the state space */ + unsigned int getStateDimension() const + { + return stateSpace_->getDimension(); + } + + /** \brief Get a measure of the space (this can be thought of as a generalization of volume) */ + double getSpaceMeasure() const + { + return stateSpace_->getMeasure(); + } + + /** @name State memory management + @{ */ + + /** \brief Allocate memory for a state */ + State *allocState() const + { + return stateSpace_->allocState(); + } + + /** \brief Allocate memory for each element of the array \e states */ + void allocStates(std::vector &states) const + { + for (auto &state : states) + state = stateSpace_->allocState(); + } + + /** \brief Free the memory of a state */ + void freeState(State *state) const + { + stateSpace_->freeState(state); + } + + /** \brief Free the memory of an array of states */ + void freeStates(std::vector &states) const + { + for (auto &state : states) + stateSpace_->freeState(state); + } + + /** \brief Copy a state to another */ + void copyState(State *destination, const State *source) const + { + stateSpace_->copyState(destination, source); + } + + /** \brief Clone a state */ + State *cloneState(const State *source) const + { + return stateSpace_->cloneState(source); + } + + /** @} */ + + /** @name Sampling of valid states + @{ */ + + /** \brief Allocate a uniform state sampler for the state space */ + StateSamplerPtr allocStateSampler() const + { + return stateSpace_->allocStateSampler(); + } + + /** \brief Allocate an instance of a valid state sampler for this space. If setValidStateSamplerAllocator() + was previously called, + the specified allocator is used to produce the state sampler. Otherwise, a + ompl::base::UniformValidStateSampler() is + allocated. */ + ValidStateSamplerPtr allocValidStateSampler() const; + + /** \brief Set the allocator to use for a valid state sampler. This replaces the default uniform valid state + sampler. This call can be made at any time, but it should not be changed while + ompl::base::Planner::solve() is executing */ + void setValidStateSamplerAllocator(const ValidStateSamplerAllocator &vssa); + + /** \brief Clear the allocator used for the valid state sampler. This will revert to using the uniform valid + * state sampler (the default). */ + void clearValidStateSamplerAllocator(); + + /** @}*/ + + /** @name Primitives typically used by motion planners + @{ */ + + /** \brief Get the maximum extent of the space we are + planning in. This is the maximum distance that could + be reported between any two given states */ + double getMaximumExtent() const + { + return stateSpace_->getMaximumExtent(); + } + + /** \brief Find a valid state near a given one. If the given state is valid, it will be returned itself. + * The two passed state pointers need not point to different memory. Returns true on success. + * \param state the location at which to store the valid state, if one is found. This location may be + * modified even if no valid state is found. + * \param near a state that may be invalid near which we would like to find a valid state + * \param distance the maximum allowed distance between \e state and \e near + * \param attempts the algorithm works by sampling states near state \e near. This parameter defines the + * maximum number of sampling attempts + */ + bool searchValidNearby(State *state, const State *near, double distance, unsigned int attempts) const; + + /** \brief Find a valid state near a given one. If the given state is valid, it will be returned itself. + * The two passed state pointers need not point to different memory. Returns true on success. + * \param sampler the valid state sampler to use when attemting to find a valid sample. + * \param state the location at which to store the valid state, if one is found. This location may be + * modified even if no valid state is found. + * \param near a state that may be invalid near which we would like to find a valid state + * \param distance the maximum allowed distance between \e state and \e near + */ + bool searchValidNearby(const ValidStateSamplerPtr &sampler, State *state, const State *near, + double distance) const; + + /** \brief Produce a valid motion starting at \e start by randomly bouncing off of invalid states. The start + * state \e start is not included in the computed motion (\e states). Returns the number of elements written + * to \e states (less or equal to \e steps). + * \param sss the state space sampler to use + * \param start the state at which to start bouncing + * \param steps the number of bouncing steps to take + * \param states the location at which generated states will be stored + * \param alloc flag indicating whether memory should be allocated for \e states */ + unsigned int randomBounceMotion(const StateSamplerPtr &sss, const State *start, unsigned int steps, + std::vector &states, bool alloc) const; + + /** \brief Incrementally check if the path between two motions is valid. Also compute the last state that + was + valid and the time of that state. The time is used to parametrize the motion from s1 to s2, s1 being at + t = + 0 and s2 being at t = 1. This function assumes s1 is valid. + \param s1 start state of the motion to be checked (assumed to be valid) + \param s2 final state of the motion to be checked + \param lastValid first: storage for the last valid state (may be nullptr); this need not be different + from \e s1 or \e s2. second: the time (between 0 and 1) of the last valid state, on the motion from \e + s1 to \e s2 */ + virtual bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const + { + return motionValidator_->checkMotion(s1, s2, lastValid); + } + + /** \brief Check if the path between two states (from \e s1 to \e s2) is valid, using the MotionValidator. + * This function assumes \e s1 is valid. */ + virtual bool checkMotion(const State *s1, const State *s2) const + { + return motionValidator_->checkMotion(s1, s2); + } + + /** \brief Incrementally check if a sequence of states is valid. Given a vector of states, this routine only + checks the first \e count elements and marks the index of the first invalid state + \param states the array of states to be checked + \param count the number of states to be checked in the array (0 to \e count) + \param firstInvalidStateIndex location to store the first invalid state index. Unmodified if the + function returns true */ + bool checkMotion(const std::vector &states, unsigned int count, + unsigned int &firstInvalidStateIndex) const; + + /** \brief Check if a sequence of states is valid using subdivision. */ + bool checkMotion(const std::vector &states, unsigned int count) const; + + /** \brief Get \e count states that make up a motion between \e s1 and \e s2. Returns the number of states + that were added to \e states. These states are not checked for validity. + If \e states.size() >= count or \e alloc is true, the returned value is equal to \e count (or \e count + + 2, if \e endpoints is true). + Otherwise, fewer states can be returned. + \param s1 the start state of the considered motion + \param s2 the end state of the considered motion + \param states the computed set of states along the specified motion + \param count the number of intermediate states to compute + \param endpoints flag indicating whether \e s1 and \e s2 are to be included in states + \param alloc flag indicating whether memory is to be allocated automatically + */ + virtual unsigned int getMotionStates(const State *s1, const State *s2, std::vector &states, + unsigned int count, bool endpoints, bool alloc) const; + + /** \brief Get the total number of motion segments checked by the MotionValidator so far */ + unsigned int getCheckedMotionCount() const + { + return motionValidator_->getCheckedMotionCount(); + } + + /** @}*/ + + /** @name Routines for inferring information about the state space + @{ */ + + /** \brief Estimate probability of sampling a valid state. setup() is assumed to have been called. */ + double probabilityOfValidState(unsigned int attempts) const; + + /** \brief Estimate the length of a valid motion. setup() is assumed to have been called.*/ + double averageValidMotionLength(unsigned int attempts) const; + + /** \brief Estimate the number of samples that can be drawn per second, using the sampler returned by + * allocStateSampler() */ + void samplesPerSecond(double &uniform, double &near, double &gaussian, unsigned int attempts) const; + + /** \brief Print information about the current instance of the state space */ + virtual void printSettings(std::ostream &out = std::cout) const; + + /** \brief Print properties of the current instance of the state space */ + virtual void printProperties(std::ostream &out = std::cout) const; + + /** \brief Get the combined parameters for the classes that the space information manages */ + ParamSet ¶ms() + { + return params_; + } + + /** \brief Get the combined parameters for the classes that the space information manages */ + const ParamSet ¶ms() const + { + return params_; + } + + /** \brief Perform additional setup tasks (run once, + before use). If state validity checking resolution has + not been set, estimateMaxResolution() is called to + estimate it. */ + virtual void setup(); + + /** \brief Return true if setup was called */ + bool isSetup() const; + + protected: + /** \brief Set default motion validator for the state space */ + void setDefaultMotionValidator(); + + /** \brief The state space planning is to be performed in */ + StateSpacePtr stateSpace_; + + /** \brief The instance of the state validity checker used for determining the validity of states in the + * planning process */ + StateValidityCheckerPtr stateValidityChecker_; + + /** \brief The instance of the motion validator to use when determining the validity of motions in the + * planning process */ + MotionValidatorPtr motionValidator_; + + /** \brief Flag indicating whether setup() has been called on this instance */ + bool setup_; + + /** \brief The optional valid state sampler allocator */ + ValidStateSamplerAllocator vssa_; + + /** \brief Combined parameters for the contained classes */ + ParamSet params_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/State.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/State.h new file mode 100644 index 00000000..63b58d76 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/State.h @@ -0,0 +1,133 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_ +#define OMPL_BASE_STATE_ + +#include + +namespace ompl +{ + namespace base + { + /** \brief Definition of an abstract state. + + See \ref stateAlloc and \ref stateOps. */ + class State + { + private: + /** \brief Disable copy-constructor */ + State(const State &) = delete; + + /** \brief Disable copy operator */ + const State &operator=(const State &) = delete; + + protected: + State() = default; + + virtual ~State() = default; + + public: + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + }; + + /** \brief Definition of a compound state */ + class CompoundState : public State + { + public: + CompoundState() = default; + + ~CompoundState() override = default; + + /** \brief Cast a component of this instance to a desired type. */ + template + const T *as(unsigned int index) const + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(components[index]); + } + + /** \brief Cast a component of this instance to a desired type. */ + template + T *as(const unsigned int index) + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(components[index]); + } + + /** \brief Access const element ith component. This + does not check whether the index is within bounds. */ + const State *operator[](unsigned int i) const + { + return components[i]; + } + + /** \brief Access element ith component. This + does not check whether the index is within bounds. */ + State *operator[](unsigned int i) + { + return components[i]; + } + + /** \brief The components that make up a compound state */ + State **components{nullptr}; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSampler.h new file mode 100644 index 00000000..a3c36e52 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSampler.h @@ -0,0 +1,195 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_SAMPLER_ +#define OMPL_BASE_STATE_SAMPLER_ + +#include "ompl/base/State.h" +#include "ompl/util/RandomNumbers.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(StateSpace); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::StateSampler */ + OMPL_CLASS_FORWARD(StateSampler); + /// @endcond + + /** \class ompl::base::StateSamplerPtr + \brief A shared pointer wrapper for ompl::base::StateSampler */ + + /** \brief Abstract definition of a state space sampler. */ + class StateSampler + { + public: + // non-copyable + StateSampler(const StateSampler &) = delete; + StateSampler &operator=(const StateSampler &) = delete; + + /** \brief Constructor */ + StateSampler(const StateSpace *space) : space_(space) + { + } + + virtual ~StateSampler() = default; + + /** \brief Sample a state */ + virtual void sampleUniform(State *state) = 0; + + /** \brief Sample a state near another, within a neighborhood controlled by a distance parameter. + + Typically, StateSampler-derived classes will return in `state` a + state that is uniformly distributed within a ball with radius + `distance` defined by the distance function from the corresponding + state space. However, this is not guaranteed. For example, the + default state sampler for the RealVectorStateSpace returns samples + uniformly distributed using L_inf distance, while the default + distance function is L_2 distance. + */ + virtual void sampleUniformNear(State *state, const State *near, double distance) = 0; + + /** \brief Sample a state using a Gaussian distribution with given \e mean and standard deviation (\e + stdDev). + + As with sampleUniform, the implementation of sampleGaussian is + specific to the derived class and few assumptions can be made + about the distance between `state` and `mean`. + */ + virtual void sampleGaussian(State *state, const State *mean, double stdDev) = 0; + + protected: + /** \brief The state space this sampler samples */ + const StateSpace *space_; + + /** \brief An instance of a random number generator */ + RNG rng_; + }; + + /** \brief Definition of a compound state sampler. This is useful to construct samplers for compound states. */ + class CompoundStateSampler : public StateSampler + { + public: + /** \brief Constructor */ + CompoundStateSampler(const StateSpace *space) : StateSampler(space), samplerCount_(0) + { + } + + /** \brief Destructor. This frees the added samplers as well. */ + ~CompoundStateSampler() override = default; + + /** \brief Add a sampler as part of the new compound + sampler. This sampler is used to sample part of the + compound state. When sampling near a state, the + compound sampler calls in to added samplers. The + distance passed to the called samplers is adjusted + according to the specified importance. */ + virtual void addSampler(const StateSamplerPtr &sampler, double weightImportance); + + void sampleUniform(State *state) override; + + /** \brief Call sampleUniformNear for each of the subspace states + with distance scaled by the corresponding subspace weight. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + + /** \brief Call sampleGaussian for each of the subspace states + with stdDev scaled by the corresponding subspace weight. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + protected: + /** \brief The samplers that are composed */ + std::vector samplers_; + + /** \brief The weight of each sampler (used when sampling near a state) */ + std::vector weightImportance_; + + private: + /** \brief The number of samplers that are composed */ + unsigned int samplerCount_; + }; + + /** \brief Construct a sampler that samples only within a subspace of the space */ + class SubspaceStateSampler : public StateSampler + { + public: + /** \brief Construct a sampler for \e space but only sample components common to \e subspace. Use \e weight + * as a multiplicative factor for \e distance and \e stdDev in the sampleUniformNear() and sampleGaussian() + * functions. */ + SubspaceStateSampler(const StateSpace *space, const StateSpace *subspace, double weight); + ~SubspaceStateSampler() override; + + void sampleUniform(State *state) override; + + void sampleUniformNear(State *state, const State *near, double distance) override; + + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + protected: + /** \brief The subspace to sample */ + const StateSpace *subspace_; + + /** \brief The sampler for the subspace */ + StateSamplerPtr subspaceSampler_; + + /** \brief The weigth factor to multiply distance and stdDev when sampling in the vicinity of a state */ + double weight_; + + /** \brief The names of common subspaces between \e space_ and \e subspace_; these are the ones copied after + * sampling a state */ + std::vector subspaces_; + + private: + /** \brief Temporary work area */ + State *work_; + + /** \brief Temporary work area */ + State *work2_; + }; + + /** \brief Definition of a function that can allocate a state sampler */ + using StateSamplerAllocator = std::function; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSamplerArray.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSamplerArray.h new file mode 100644 index 00000000..5c276699 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSamplerArray.h @@ -0,0 +1,148 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_SAMPLER_ARRAY_ +#define OMPL_BASE_STATE_SAMPLER_ARRAY_ + +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/ValidStateSampler.h" +#include + +namespace ompl +{ + namespace base + { + /** \brief Depending on the type of state sampler, we have different allocation routines + + This struct will provide that allocation routine, + depending on the template argument of ompl::base::SamplerType.*/ + template + struct SamplerSelector + { + }; + + /** \cond IGNORE */ + template <> + struct SamplerSelector + { + using Sampler = StateSampler; + using SamplerPtr = StateSamplerPtr; + + SamplerPtr allocStateSampler(const SpaceInformation *si) + { + return si->allocStateSampler(); + } + }; + + template <> + struct SamplerSelector + { + using Sampler = ValidStateSampler; + using SamplerPtr = ValidStateSamplerPtr; + + SamplerPtr allocStateSampler(const SpaceInformation *si) + { + return si->allocValidStateSampler(); + } + }; + /** \endcond */ + + /** \brief Class to ease the creation of a set of samplers. This is especially useful for multi-threaded + * planners. */ + template + class StateSamplerArray + { + public: + /** \brief Pointer to the type of sampler allocated */ + using SamplerPtr = typename SamplerSelector::SamplerPtr; + + /** \brief The type of sampler allocated */ + using Sampler = typename SamplerSelector::Sampler; + + /** \brief Constructor */ + StateSamplerArray(const SpaceInformationPtr &si) : si_(si.get()) + { + } + + /** \brief Constructor */ + StateSamplerArray(const SpaceInformation *si) : si_(si) + { + } + + ~StateSamplerArray() = default; + + /** \brief Access operator for a specific sampler. For + performance reasons, the bounds are not checked. */ + Sampler *operator[](std::size_t index) const + { + return samplers_[index].get(); + } + + /** \brief Create or release some state samplers */ + void resize(std::size_t count) + { + if (samplers_.size() > count) + samplers_.resize(count); + else if (samplers_.size() < count) + { + samplers_.resize(count); + for (auto &sampler : samplers_) + sampler = ss_.allocStateSampler(si_); + } + } + + /** \brief Get the count of samplers currently available */ + std::size_t size() const + { + return samplers_.size(); + } + + /** \brief Clear all allocated samplers */ + void clear() + { + resize(0); + } + + private: + const SpaceInformation *si_; + SamplerSelector ss_; + std::vector samplers_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpace.h new file mode 100644 index 00000000..90e882e4 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpace.h @@ -0,0 +1,841 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_SPACE_ +#define OMPL_BASE_STATE_SPACE_ + +#include "ompl/base/State.h" +#include "ompl/base/StateSpaceTypes.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/ProjectionEvaluator.h" +#include "ompl/base/GenericParam.h" +#include "ompl/util/Console.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::StateSpace */ + OMPL_CLASS_FORWARD(StateSpace); + /// @endcond + + /** \class ompl::base::StateSpacePtr + \brief A shared pointer wrapper for ompl::base::StateSpace */ + + /** \brief Representation of a space in which planning can be + performed. Topology specific sampling, interpolation and distance + are defined. + + See \ref implementingStateSpaces. */ + class StateSpace + { + public: + // non-copyable + StateSpace(const StateSpace &) = delete; + StateSpace &operator=(const StateSpace &) = delete; + + /** \brief Define the type of state allocated by this space */ + using StateType = ompl::base::State; + + /** \brief Constructor. Assigns a @b unique name to the space */ + StateSpace(); + + virtual ~StateSpace(); + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are casting to is indeed a state space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are casting to is indeed a state space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Representation of the address of a substate in a state. This structure stores the indexing + * information needed to access a particular substate of a state */ + struct SubstateLocation + { + /** \brief In a complex state space there may be multiple + compound state spaces that make up an even larger + compound space. This array indicates the sequence of + indices of the subspaces that need to be followed to + get to the component of the state that is of interest. */ + std::vector chain; + + /** \brief The space that is reached if the chain above is followed on the state space */ + const StateSpace *space; + }; + + /** \brief Representation of the address of a value in a state. This structure stores the indexing + * information needed to access elements of a state (no pointer values are stored) */ + struct ValueLocation + { + /** \brief Location of the substate that contains the pointed to value */ + SubstateLocation stateLocation; + + /** \brief The index of the value to be accessed, within the substate location above */ + std::size_t index; + }; + + /** \brief Flags to use in a bit mask for state space sanity checks. Some basic checks do not have flags + associated (they are always executed; for example, + whether copyState() works as expected) */ + enum SanityChecks + { + + /// \brief Check whether the distances between non-equal states is strictly positive + /// (StateSpace::distance()) + STATESPACE_DISTANCE_DIFFERENT_STATES = (1 << 1), + + /// \brief Check whether the distance function is symmetric (StateSpace::distance()) + STATESPACE_DISTANCE_SYMMETRIC = (1 << 2), + + /// \brief Check whether calling StateSpace::interpolate() works as expected + STATESPACE_INTERPOLATION = (1 << 3), + + /// \brief Check whether the triangle inequality holds when using StateSpace::interpolate() and + /// StateSpace::distance() + STATESPACE_TRIANGLE_INEQUALITY = (1 << 4), + + /// \brief Check whether the StateSpace::distance() is bounded by StateSpace::getExtent() + STATESPACE_DISTANCE_BOUND = (1 << 5), + + /// \brief Check whether sampled states are always within bounds + STATESPACE_RESPECT_BOUNDS = (1 << 6), + + /// \brief Check that enforceBounds() does not modify the contents of states that are within bounds + STATESPACE_ENFORCE_BOUNDS_NO_OP = (1 << 7), + + /// \brief Check whether the StateSpace::serialize() and StateSpace::deserialize() work as expected + STATESPACE_SERIALIZATION = (1 << 8) + }; + + /** @name Generic functionality for state spaces + @{ */ + + /** \brief Check if the state space is compound */ + virtual bool isCompound() const; + + /** \brief Check if the set of states is discrete + + \note In fact, because of limited numerical precision, + the representation of all spaces is discrete; this + function returns true if the corresponding + mathematical object is a discrete one. */ + virtual bool isDiscrete() const; + + /** \brief Check if this is a hybrid state space (i.e., both discrete and continuous components exist)*/ + virtual bool isHybrid() const; + + /** \brief Return true if the distance function associated with the space + is a metric */ + virtual bool isMetricSpace() const + { + return true; + } + + /** \brief Check if the distance function on this state space is symmetric, i.e. distance(s1,s2) = + * distance(s2,s1). Default implementation returns true.*/ + virtual bool hasSymmetricDistance() const; + + /** \brief Check if the interpolation function on this state space is symmetric, i.e. interpolate(from, to, + * t, state) = interpolate(to, from, 1-t, state). Default implementation returns true.*/ + virtual bool hasSymmetricInterpolate() const; + + /** \brief Get the name of the state space */ + const std::string &getName() const; + + /** \brief Set the name of the state space */ + void setName(const std::string &name); + + /** \brief Get the type of the state space. The type can be + used to verify whether two space instances are of + the same type (e.g., SO2) */ + int getType() const + { + return type_; + } + + /** \brief Return true if \e other is a space included (perhaps equal, perhaps a subspace) in this one. */ + bool includes(const StateSpacePtr &other) const; + + /** \brief Return true if \e other is a space included (perhaps equal, perhaps a subspace) in this one. */ + bool includes(const StateSpace *other) const; + + /** \brief Return true if \e other is a space that is either included (perhaps equal, perhaps a subspace) + in this one, or all of its subspaces are included in this one. */ + bool covers(const StateSpacePtr &other) const; + + /** \brief Return true if \e other is a space that is either included (perhaps equal, perhaps a subspace) + in this one, or all of its subspaces are included in this one. */ + bool covers(const StateSpace *other) const; + + /** \brief Get the parameters for this space */ + ParamSet ¶ms() + { + return params_; + } + + /** \brief Get the parameters for this space */ + const ParamSet ¶ms() const + { + return params_; + } + + /** \brief When performing discrete validation of motions, + the length of the longest segment that does not + require state validation needs to be specified. This + function returns this length, for this state space, as a + fraction of the space's maximum extent. */ + virtual double getLongestValidSegmentFraction() const; + + /** \brief When performing discrete validation of motions, + the length of the longest segment that does not + require state validation needs to be specified. This + function sets this length as a fraction of the + space's maximum extent. + + \note This function's effect is not considered until + after setup() has been called. For immediate effects + (i.e., during planning) use + setValidSegmentCountFactor() */ + virtual void setLongestValidSegmentFraction(double segmentFraction); + + /** \brief Count how many segments of the "longest valid length" fit on the motion from \e state1 to \e + * state2 */ + virtual unsigned int validSegmentCount(const State *state1, const State *state2) const; + + /** \brief Set \e factor to be the value to multiply the + return value of validSegmentCount(). By default, this + value is 1. The higher the value, the smaller the size + of the segments considered valid. The effect of this + function is immediate (setup() does not need to be + called). */ + virtual void setValidSegmentCountFactor(unsigned int factor); + + /** \brief Get the value used to multiply the return value of validSegmentCount().*/ + virtual unsigned int getValidSegmentCountFactor() const; + + /** \brief Get the longest valid segment at the time setup() was called. */ + virtual double getLongestValidSegmentLength() const; + + /** \brief Compute an array of ints that uniquely identifies the structure of the state space. + The first element of the signature is the number of integers that follow */ + virtual void computeSignature(std::vector &signature) const; + + /** @} */ + + /** @name Functionality specific to state spaces (to be implemented by derived state spaces) + @{ */ + + /** \brief Get the dimension of the space (not the dimension of the surrounding ambient space) */ + virtual unsigned int getDimension() const = 0; + + /** \brief Get the maximum value a call to distance() can return (or an upper bound). + For unbounded state spaces, this function can return infinity. + + \note Tight upper bounds are preferred because the value of the extent is used in + the automatic computation of parameters for planning. If the bounds are less tight, + the automatically computed parameters will be less useful.*/ + virtual double getMaximumExtent() const = 0; + + /** \brief Get a measure of the space (this can be thought of as a generalization of volume) */ + virtual double getMeasure() const = 0; + + /** \brief Bring the state within the bounds of the state space. For unbounded spaces this + function can be a no-op. */ + virtual void enforceBounds(State *state) const = 0; + + /** \brief Check if a state is inside the bounding box. For unbounded spaces this function + can always return true. */ + virtual bool satisfiesBounds(const State *state) const = 0; + + /** \brief Copy a state to another. The memory of source and destination should NOT overlap. + \note For more advanced state copying methods (partial copy, for example), see \ref advancedStateCopy. + */ + virtual void copyState(State *destination, const State *source) const = 0; + + /** \brief Clone a state*/ + State *cloneState(const State *source) const; + + /** \brief Computes distance between two states. This function satisfies the properties of a + metric if isMetricSpace() is true, and its return value will always be between 0 and getMaximumExtent() + */ + virtual double distance(const State *state1, const State *state2) const = 0; + + /** \brief Get the number of chars in the serialization of a state in this space */ + virtual unsigned int getSerializationLength() const; + + /** \brief Write the binary representation of \e state to \e serialization */ + virtual void serialize(void *serialization, const State *state) const; + + /** \brief Read the binary representation of a state from \e serialization and write it to \e state */ + virtual void deserialize(State *state, const void *serialization) const; + + /** \brief Checks whether two states are equal */ + virtual bool equalStates(const State *state1, const State *state2) const = 0; + + /** \brief Computes the state that lies at time @e t in [0, 1] on the segment that connects @e from state to + @e to state. + The memory location of @e state is not required to be different from the memory of either + @e from or @e to. */ + virtual void interpolate(const State *from, const State *to, double t, State *state) const = 0; + + /** \brief Allocate an instance of the default uniform state sampler for this space */ + virtual StateSamplerPtr allocDefaultStateSampler() const = 0; + + /** \brief Allocate an instance of the state sampler for this space. This sampler will be allocated with the + sampler allocator that was previously specified by setStateSamplerAllocator() or, if no sampler + allocator was specified, + allocDefaultStateSampler() is called */ + virtual StateSamplerPtr allocStateSampler() const; + + /** \brief Set the sampler allocator to use */ + void setStateSamplerAllocator(const StateSamplerAllocator &ssa); + + /** \brief Clear the state sampler allocator (reset to default) */ + void clearStateSamplerAllocator(); + + /** \brief Allocate a state that can store a point in the described space */ + virtual State *allocState() const = 0; + + /** \brief Free the memory of the allocated state */ + virtual void freeState(State *state) const = 0; + + /** @} */ + + /** @name Functionality specific to accessing real values in a state + @{ */ + + /** \brief Many states contain a number of double values. This function provides a means to get the + memory address of a double value from state \e state located at position \e index. The first double + value + is returned for \e index = 0. If \e index is too large (does not point to any double values in the + state), + the return value is nullptr. + + \note This function does @b not map a state to an + array of doubles. There may be components of a state + that do not correspond to double values and they are + 'invisible' to this function. Furthermore, this + function is @b slow and is not intended for use in the + implementation of planners. Ideally, state values should not be accessed by index. If accessing of + individual state elements + is however needed, getValueAddressAtLocation() provides a faster implementation. */ + virtual double *getValueAddressAtIndex(State *state, unsigned int index) const; + + /** \brief Const variant of the same function as above; */ + virtual const double *getValueAddressAtIndex(const State *state, unsigned int index) const; + + /** \brief Get the locations of values of type double contained in a state from this space. The order of the + values is + consistent with getValueAddressAtIndex(). The setup() function must have been previously called. */ + virtual const std::vector &getValueLocations() const; + + /** \brief Get the named locations of values of type double contained in a state from this space. + The setup() function must have been previously called. */ + virtual const std::map &getValueLocationsByName() const; + + /** \brief Get a pointer to the double value in \e state that \e loc points to */ + virtual double *getValueAddressAtLocation(State *state, const ValueLocation &loc) const; + + /** \brief Const variant of the same function as above; */ + virtual const double *getValueAddressAtLocation(const State *state, const ValueLocation &loc) const; + + /** \brief Get a pointer to the double value in \e state that \e name points to */ + virtual double *getValueAddressAtName(State *state, const std::string &name) const; + + /** \brief Const variant of the same function as above; */ + virtual const double *getValueAddressAtName(const State *state, const std::string &name) const; + + /** \brief Copy all the real values from a state \e source to the array \e reals using + * getValueAddressAtLocation() */ + virtual void copyToReals(std::vector &reals, const State *source) const; + + /** \brief Copy the values from \e reals to the state \e destination using getValueAddressAtLocation() */ + virtual void copyFromReals(State *destination, const std::vector &reals) const; + + /** @} */ + + /** @name Management of projections from this state space to Euclidean spaces + @{ */ + + /** \brief Register a projection for this state space under a specified name */ + void registerProjection(const std::string &name, const ProjectionEvaluatorPtr &projection); + + /** \brief Register the default projection for this state space */ + void registerDefaultProjection(const ProjectionEvaluatorPtr &projection); + + /** \brief Register the projections for this state space. Usually, this is at least the default + projection. These are implicit projections, set by the implementation of the state space. This is called + by setup(). */ + virtual void registerProjections(); + + /** \brief Get the projection registered under a specific name */ + ProjectionEvaluatorPtr getProjection(const std::string &name) const; + + /** \brief Get the default projection */ + ProjectionEvaluatorPtr getDefaultProjection() const; + + /** \brief Check if a projection with a specified name is available */ + bool hasProjection(const std::string &name) const; + + /** \brief Check if a default projection is available */ + bool hasDefaultProjection() const; + + /** \brief Get all the registered projections */ + const std::map &getRegisteredProjections() const; + + /** @} */ + + /** @name Debugging tools + @{ */ + + /** \brief Print a state to a stream */ + virtual void printState(const State *state, std::ostream &out = std::cout) const; + + /** \brief Print the settings for this state space to a stream */ + virtual void printSettings(std::ostream &out) const; + + /** \brief Print the list of registered projections. This function is also called by printSettings() */ + virtual void printProjections(std::ostream &out) const; + + /** \brief Perform sanity checks for this state space. Throws an exception if failures are found. + \note This checks if distances are always positive, whether the integration works as expected, etc. */ + virtual void sanityChecks(double zero, double eps, unsigned int flags) const; + + /** \brief Convenience function that allows derived state spaces to choose which checks + should pass (see SanityChecks flags) and how strict the checks are. This just calls sanityChecks() with + some default arguments. */ + virtual void sanityChecks() const; + + /** \brief Print a Graphviz digraph that represents the containment diagram for the state space */ + void diagram(std::ostream &out) const; + + /** \brief Print the list of all contained state space instances */ + void list(std::ostream &out) const; + + /** \brief Print a Graphviz digraph that represents the containment diagram for all the instantiated state + * spaces */ + static void Diagram(std::ostream &out); + + /** \brief Print the list of available state space instances */ + static void List(std::ostream &out); + + /** @} */ + + /** @name Operations with substates + @{ */ + + /** \brief Allocate a sampler that actually samples only components that are part of \e subspace */ + StateSamplerPtr allocSubspaceStateSampler(const StateSpacePtr &subspace) const; + + /** \brief Allocate a sampler that actually samples only components that are part of \e subspace */ + virtual StateSamplerPtr allocSubspaceStateSampler(const StateSpace *subspace) const; + + /** \brief Get the substate of \e state that is pointed to by \e loc */ + State *getSubstateAtLocation(State *state, const SubstateLocation &loc) const; + + /** \brief Get the substate of \e state that is pointed to by \e loc */ + const State *getSubstateAtLocation(const State *state, const SubstateLocation &loc) const; + + /** \brief Get the list of known substate locations (keys of the map corrspond to names of subspaces) */ + const std::map &getSubstateLocationsByName() const; + + /** \brief Get the set of subspaces that this space and \e other have in common. The computed list of \e + subspaces does + not contain spaces that cover each other, even though they may be common, as that is redundant + information. */ + void getCommonSubspaces(const StateSpacePtr &other, std::vector &subspaces) const; + + /** \brief Get the set of subspaces that this space and \e other have in common. The computed list of \e + subspaces does + not contain spaces that cover each other, even though they may be common, as that is redundant + information. */ + void getCommonSubspaces(const StateSpace *other, std::vector &subspaces) const; + + /** \brief Compute the location information for various components of the state space. Either this function + or setup() must be + called before any calls to getValueAddressAtName(), getValueAddressAtLocation() (and other functions + where those are used). */ + virtual void computeLocations(); + + /** @} */ + + /** \brief Perform final setup steps. This function is + automatically called by the SpaceInformation. If any + default projections are to be registered, this call + will set them and call their setup() functions. It is + safe to call this function multiple times. At a + subsequent call, projections that have been previously + user configured are not re-instantiated, but their + setup() method is still called. */ + virtual void setup(); + + protected: + /** \brief The name used for the default projection */ + static const std::string DEFAULT_PROJECTION_NAME; + + /** \brief A type assigned for this state space */ + int type_; + + /** \brief An optional state sampler allocator */ + StateSamplerAllocator ssa_; + + /** \brief The extent of this space at the time setup() was called */ + double maxExtent_; + + /** \brief The fraction of the longest valid segment */ + double longestValidSegmentFraction_; + + /** \brief The longest valid segment at the time setup() was called */ + double longestValidSegment_; + + /** \brief The factor to multiply the value returned by validSegmentCount(). Rarely used but useful for + * things like doubling the resolution */ + unsigned int longestValidSegmentCountFactor_; + + /** \brief List of available projections */ + std::map projections_; + + /** \brief The set of parameters for this space */ + ParamSet params_; + + /** \brief The value locations for all varliables of type double contained in a state; + The locations point to values in the same order as that returned by getValueAddressAtIndex() */ + std::vector valueLocationsInOrder_; + + /** \brief All the known value locations, by name. The names of state spaces access the first element of a + state. + RealVectorStateSpace dimensions are used to access individual dimensions. */ + std::map valueLocationsByName_; + + /** \brief All the known substat locations, by name. */ + std::map substateLocationsByName_; + + private: + /** \brief State space name */ + std::string name_; + }; + + /** \brief A space to allow the composition of state spaces */ + class CompoundStateSpace : public StateSpace + { + public: + /** \brief Define the type of state allocated by this state space */ + using StateType = ompl::base::CompoundState; + + /** \brief Construct an empty compound state space */ + CompoundStateSpace(); + + /** \brief Construct a compound state space from a list of subspaces (\e components) and their corresponding + * weights (\e weights) */ + CompoundStateSpace(const std::vector &components, const std::vector &weights); + + ~CompoundStateSpace() override = default; + + /** \brief Cast a component of this instance to a desired type. */ + template + T *as(const unsigned int index) const + { + /** \brief Make sure the type we are casting to is indeed a state space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(getSubspace(index).get()); + } + + /** \brief Cast a component of this instance to a desired type. */ + template + T *as(const std::string &name) const + { + /** \brief Make sure the type we are casting to is indeed a state space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(getSubspace(name).get()); + } + + bool isCompound() const override; + + bool isHybrid() const override; + + bool isMetricSpace() const override; + + /** @name Management of contained subspaces + @{ */ + + /** \brief Adds a new state space as part of the compound state space. For computing distances within the + compound + state space, the weight of the component also needs to be specified. */ + void addSubspace(const StateSpacePtr &component, double weight); + + /** \brief Get the number of state spaces that make up the compound state space */ + unsigned int getSubspaceCount() const; + + /** \brief Get a specific subspace from the compound state space */ + const StateSpacePtr &getSubspace(unsigned int index) const; + + /** \brief Get a specific subspace from the compound state space */ + const StateSpacePtr &getSubspace(const std::string &name) const; + + /** \brief Get the index of a specific subspace from the compound state space */ + unsigned int getSubspaceIndex(const std::string &name) const; + + /** \brief Check if a specific subspace is contained in this state space */ + bool hasSubspace(const std::string &name) const; + + /** \brief Get the weight of a subspace from the compound state space (used in distance computation) */ + double getSubspaceWeight(unsigned int index) const; + + /** \brief Get the weight of a subspace from the compound state space (used in distance computation) */ + double getSubspaceWeight(const std::string &name) const; + + /** \brief Set the weight of a subspace in the compound state space (used in distance computation) */ + void setSubspaceWeight(unsigned int index, double weight); + + /** \brief Set the weight of a subspace in the compound state space (used in distance computation) */ + void setSubspaceWeight(const std::string &name, double weight); + + /** \brief Get the list of components */ + const std::vector &getSubspaces() const; + + /** \brief Get the list of component weights */ + const std::vector &getSubspaceWeights() const; + + /** \brief Return true if the state space is locked. A value + of true means that no further spaces can be added + as components. */ + bool isLocked() const; + + /** \brief Lock this state space. This means no further + spaces can be added as components. This function can + be for instance called from the constructor of a + state space that inherits from CompoundStateSpace to + prevent the user to add further components. */ + void lock(); + /** @} */ + + /** @name Operations with substates + @{ */ + + StateSamplerPtr allocSubspaceStateSampler(const StateSpace *subspace) const override; + + /** @} */ + + /** @name Functionality specific to the state space + @{ */ + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + /** \brief When performing discrete validation of motions, + the length of the longest segment that does not + require state validation needs to be specified. This + function sets this length as a fraction of the space's + maximum extent. The call is passed to all contained subspaces */ + void setLongestValidSegmentFraction(double segmentFraction) override; + + /** \brief Count how many segments of the "longest valid length" fit on the motion from \e state1 to \e + state2. + This is the max() of the counts returned by contained subspaces. */ + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + /** @} */ + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void computeLocations() override; + + void setup() override; + + protected: + /** \brief Allocate the state components. Called by allocState(). Usually called by derived state spaces. */ + void allocStateComponents(CompoundState *state) const; + + /** \brief The state spaces that make up the compound state space */ + std::vector components_; + + /** \brief The number of components */ + unsigned int componentCount_{0u}; + + /** \brief The weight assigned to each component of the state space when computing the compound distance */ + std::vector weights_; + + /** \brief The sum of all the weights in \e weights_ */ + double weightSum_{0.0}; + + /** \brief Flag indicating whether adding further components is allowed or not */ + bool locked_{false}; + }; + + /** \addtogroup stateAndSpaceOperators + * @{ + */ + + /** \brief Construct a compound state space from two existing + state spaces. The components of this compound space are \e + a (or the components of \e a, if \e a is compound) and \e + b (or the components of \e b, if \e b is compound). + State spaces are identified by name. Duplicates are checked + for and added only once. If the compound state space would + end up containing solely one component, that component is returned + instead. */ + StateSpacePtr operator+(const StateSpacePtr &a, const StateSpacePtr &b); + + /** \brief Construct a compound state space that contains + subspaces only from \e a. If \e a is compound, \e b (or + the components from \e b, if \e b is compound) are removed + and the remaining components are returned as a compound + state space. If the compound space would end up containing solely + one component, that component is returned instead. */ + StateSpacePtr operator-(const StateSpacePtr &a, const StateSpacePtr &b); + + /** \brief Construct a compound state space that contains + subspaces only from \e a, except for maybe the one named \e name */ + StateSpacePtr operator-(const StateSpacePtr &a, const std::string &name); + + /** \brief Construct a compound state space that contains + subspaces that are in both \e a and \e b */ + StateSpacePtr operator*(const StateSpacePtr &a, const StateSpacePtr &b); + /** @} */ + + /** \defgroup advancedStateCopy Advanced methods for copying states + * @{ + */ + + /** \brief The possible outputs for an advanced copy operation */ + enum AdvancedStateCopyOperation + { + /** \brief No data was copied */ + NO_DATA_COPIED = 0, + + /** \brief Some data was copied */ + SOME_DATA_COPIED = 1, + + /** \brief All data was copied */ + ALL_DATA_COPIED = 2 + }; + + /** \brief Copy data from \e source (state from space \e + sourceS) to \e dest (state from space \e destS) on a + component by component basis. State spaces are matched by + name. If the state space \e destS contains any subspace + whose name matches any subspace of the state space \e + sourceS, the corresponding state components are + copied. */ + AdvancedStateCopyOperation copyStateData(const StateSpacePtr &destS, State *dest, const StateSpacePtr &sourceS, + const State *source); + + /** \brief Copy data from \e source (state from space \e + sourceS) to \e dest (state from space \e destS) on a + component by component basis. State spaces are matched by + name. If the state space \e destS contains any subspace + whose name matches any subspace of the state space \e + sourceS, the corresponding state components are + copied. */ + AdvancedStateCopyOperation copyStateData(const StateSpace *destS, State *dest, const StateSpace *sourceS, + const State *source); + + /** \brief Copy data from \e source (state from space \e + sourceS) to \e dest (state from space \e destS) but only + for the subspaces indicated by name in \e subspaces. This + uses StateSpace::getSubstateLocationsByName(). + \note For efficiency reasons it is a good idea usually to make sure the elements of \e subspaces are not + subspaces of each other */ + AdvancedStateCopyOperation copyStateData(const StateSpacePtr &destS, State *dest, const StateSpacePtr &sourceS, + const State *source, const std::vector &subspaces); + + /** \brief Copy data from \e source (state from space \e + sourceS) to \e dest (state from space \e destS) but only + for the subspaces indicated by name in \e subspaces. This + uses StateSpace::getSubstateLocationsByName(). + \note For efficiency reasons it is a good idea usually to make sure the elements of \e subspaces are not + subspaces of each other */ + AdvancedStateCopyOperation copyStateData(const StateSpace *destS, State *dest, const StateSpace *sourceS, + const State *source, const std::vector &subspaces); + /** @} */ + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpaceTypes.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpaceTypes.h new file mode 100644 index 00000000..1766d6bd --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpaceTypes.h @@ -0,0 +1,109 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_SPACE_TYPES_ +#define OMPL_BASE_STATE_SPACE_TYPES_ + +namespace ompl +{ + namespace base + { + /** \brief The type of a state space */ + enum StateSpaceType + { + + /** \brief Unset type; this is the default type */ + STATE_SPACE_UNKNOWN = 0, + + /** \brief ompl::base::RealVectorStateSpace */ + STATE_SPACE_REAL_VECTOR = 1, + + /** \brief ompl::base::SO2StateSpace */ + STATE_SPACE_SO2 = 2, + + /** \brief ompl::base::SO3StateSpace */ + STATE_SPACE_SO3 = 3, + + /** \brief ompl::base::SE2StateSpace */ + STATE_SPACE_SE2 = 4, + + /** \brief ompl::base::SE3StateSpace */ + STATE_SPACE_SE3 = 5, + + /** \brief ompl::base::TimeStateSpace */ + STATE_SPACE_TIME = 6, + + /** \brief ompl::base::DiscreteStateSpace */ + STATE_SPACE_DISCRETE = 7, + + /** \brief ompl::base::DubinsStateSpace */ + STATE_SPACE_DUBINS = 8, + + /** \brief ompl::base::ReedsSheppStateSpace */ + STATE_SPACE_REEDS_SHEPP = 9, + + /** \brief ompl::base::MobiusStateSpace */ + STATE_SPACE_MOBIUS = 10, + + /** \brief ompl::base::SphereStateSpace */ + STATE_SPACE_SPHERE = 11, + + /** \brief ompl::base::TorusStateSpace */ + STATE_SPACE_TORUS = 12, + + /** \brief ompl::base::KleinBottleStateSpace */ + STATE_SPACE_KLEIN_BOTTLE = 13, + + /** \brief ompl::base::VanaStateSpace */ + STATE_SPACE_VANA = 14, + + /** \brief ompl::base::OwenStateSpace */ + STATE_SPACE_OWEN = 15, + + /** \brief ompl::base::VanaOwenStateSpace */ + STATE_SPACE_VANA_OWEN = 16, + + /** \brief ompl::base::TrochoidStateSpace */ + STATE_SPACE_TROCHOID = 17, + + /** \brief Number of state space types; To add new types, + use values that are larger than the count*/ + STATE_SPACE_TYPE_COUNT + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateStorage.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateStorage.h new file mode 100644 index 00000000..1c16c8da --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateStorage.h @@ -0,0 +1,286 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_STORAGE_ +#define OMPL_BASE_STATE_STORAGE_ + +#include "ompl/base/StateSpace.h" +#include +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::StateStorage */ + OMPL_CLASS_FORWARD(StateStorage); + /// @endcond + + /** \brief Manage loading and storing for a set of states of a specified state space + + \deprecated This class is deprecated and will be removed in the future. Please use the improved + PlannerDataStorage. + */ + class StateStorage + { + public: + /** \brief The state space to store states for is specified as argument */ + StateStorage(StateSpacePtr space); + virtual ~StateStorage(); + + /** \brief Get the state space this class maintains states for */ + const StateSpacePtr &getStateSpace() const + { + return space_; + } + + /** \brief Load a set of states from a specified file */ + void load(const char *filename); + + /** \brief Load a set of states from a stream */ + virtual void load(std::istream &in); + + /** \brief Save a set of states to a file */ + void store(const char *filename); + + /** \brief Save a set of states to a stream */ + virtual void store(std::ostream &out); + + /** \brief Add a state to the set of states maintained by + this storage structure. The state is copied to internal storage */ + virtual void addState(const State *state); + + /** \brief Generate \e count states uniformly at random and store them in this structure */ + virtual void generateSamples(unsigned int count); + + /** \brief Clear the stored states. This frees all the memory */ + virtual void clear(); + + /** \brief Return the number of stored states */ + std::size_t size() const + { + return states_.size(); + } + + /** \brief Get the stored states */ + const std::vector &getStates() const + { + return states_; + } + + /** \brief Get a particular state for non-const access */ + State *getState(unsigned int index) + { + assert(states_.size() > index); + return const_cast(states_[index]); + } + + /** \brief Get a particular state */ + const State *getState(unsigned int index) const + { + assert(states_.size() > index); + return states_[index]; + } + + /** \brief Return a flag that indicates whether there is metadata associated to the states in this storage + */ + bool hasMetadata() const + { + return hasMetadata_; + } + + /** \brief Sort the states according to the less-equal operator \e op. Metadata is NOT sorted; + if metadata was added, the index values of the metadata will not match after the sort. */ + void sort(const std::function &op); + + /** \brief Get a sampler allocator to a sampler that can be specified for a StateSpace, such that all + sampled + states are actually from this storage structure. */ + StateSamplerAllocator getStateSamplerAllocator() const; + + /** \brief Get a sampler allocator to a sampler that can be specified for a StateSpace, such that all + sampled + states are actually from this storage structure at an index less than or equal to \e until */ + StateSamplerAllocator getStateSamplerAllocatorRangeUntil(std::size_t until) const; + + /** \brief Get a sampler allocator to a sampler that can be specified for a StateSpace, such that all + sampled + states are actually from this storage structure at an index above or equal to \e after */ + StateSamplerAllocator getStateSamplerAllocatorRangeAfter(std::size_t after) const; + + /** \brief Get a sampler allocator to a sampler that can be specified for a StateSpace, such that all + sampled + states are actually from this storage structure at an index in the range [\e from, \e to] (inclusive) */ + virtual StateSamplerAllocator getStateSamplerAllocatorRange(std::size_t from, std::size_t to) const; + + /** \brief Output the set of states to a specified stream, in a human readable fashion */ + virtual void print(std::ostream &out = std::cout) const; + + protected: + /** \brief Information stored at the beginning of the archive */ + struct Header + { + /** \brief OMPL specific marker (fixed value) */ + std::uint_fast32_t marker; + + /** \brief Number of states stored in the archive */ + std::size_t state_count; + + /** \brief Signature of state space that allocated the saved states (see + * ompl::base::StateSpace::computeSignature()) */ + std::vector signature; + + /** \brief boost::serialization routine */ + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar & marker; + ar & state_count; + ar & signature; + } + }; + + /** \brief Load the states from a binary archive \e ia, given the loaded header is \e h */ + virtual void loadStates(const Header &h, boost::archive::binary_iarchive &ia); + + /** \brief Load the state metadata from a binary archive + \e ia, given the loaded header is \e h. No metadata is + actually loaded unless the StateStorageWithMetadata + class is used.*/ + virtual void loadMetadata(const Header &h, boost::archive::binary_iarchive &ia); + + /** \brief Store the states to a binary archive \e oa, given the stored header is \e h */ + virtual void storeStates(const Header &h, boost::archive::binary_oarchive &oa); + + /** \brief Save the state metadata to a binary archive + \e oa, given the stored header is \e h. No metadata is + actually saved unless the StateStorageWithMetadata + class is used.*/ + virtual void storeMetadata(const Header &h, boost::archive::binary_oarchive &oa); + + /** \brief Free the memory allocated for states */ + void freeMemory(); + + /** \brief State space that corresponds to maintained states */ + StateSpacePtr space_; + + /** \brief The list of maintained states */ + std::vector states_; + + /** \brief Flag indicating whether there is metadata associated to the states in this storage */ + bool hasMetadata_; + }; + + /** \brief State storage that allows storing state metadata as well + \tparam M the datatype for the stored metadata. boost::serialization operation needs to be defined */ + template + class StateStorageWithMetadata : public StateStorage + { + public: + /** \brief the datatype of the metadata */ + using MetadataType = M; + + /** \brief The state space to store states for is specified as argument */ + StateStorageWithMetadata(const StateSpacePtr &space) : StateStorage(space) + { + hasMetadata_ = true; + } + + /** \brief Add a state to the set of states maintained by + this storage structure. The state is copied to + internal storage and metadata with default values is stored as well. */ + void addState(const State *state) override + { + addState(state, M()); + } + + /** \brief Add a state to the set of states maintained by + this storage structure. The state is copied to internal storage. Corresponding metadata is stored too. + */ + virtual void addState(const State *state, const M &metadata) + { + StateStorage::addState(state); + metadata_.push_back(metadata); + } + + void clear() override + { + StateStorage::clear(); + metadata_.clear(); + } + + /** \brief Get const access to the metadata of a state at a particular index */ + const M &getMetadata(unsigned int index) const + { + assert(metadata_.size() > index); + return metadata_[index]; + } + + /** \brief Get write access to the metadata of a state at a particular index */ + M &getMetadata(unsigned int index) + { + assert(metadata_.size() > index); + return metadata_[index]; + } + + protected: + void loadMetadata(const Header & /*h*/, boost::archive::binary_iarchive &ia) override + { + // clear default metadata that was added by StateStorage::loadStates() + metadata_.clear(); + ia >> metadata_; + } + + void storeMetadata(const Header & /*h*/, boost::archive::binary_oarchive &oa) override + { + oa << metadata_; + } + + /** \brief The metadata for each state */ + std::vector metadata_; + }; + + /** \brief Storage of states where the metadata is a vector of indices. This is is typically used to store a + * graph */ + using GraphStateStorage = StateStorageWithMetadata>; + using GraphStateStoragePtr = std::shared_ptr; + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateValidityChecker.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateValidityChecker.h new file mode 100644 index 00000000..51d52025 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateValidityChecker.h @@ -0,0 +1,198 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_STATE_VALIDITY_CHECKER_ +#define OMPL_BASE_STATE_VALIDITY_CHECKER_ + +#include "ompl/base/State.h" +#include "ompl/util/ClassForward.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::StateValidityChecker */ + OMPL_CLASS_FORWARD(StateValidityChecker); + /// @endcond + + /** \class ompl::base::StateValidityCheckerPtr + \brief A shared pointer wrapper for ompl::base::StateValidityChecker */ + + /** \brief Properties that a state validity checker may have */ + struct StateValidityCheckerSpecs + { + /** \brief Specify the type of clearance computation */ + enum ClearanceComputationType + { + /// Clearance computation is not implemented. + NONE = 0, + /// Exact clearance computation is available. + EXACT, + /// Some approximation of clearance is computed, but it is not clear if this is above or below the exact + /// clearance. + APPROXIMATE, + /// A lower bound on clearance is computed. + BOUNDED_APPROXIMATE, + }; + + StateValidityCheckerSpecs() = default; + + /** \brief Value indicating the kind of clearance computation this + StateValidityChecker can compute (if any). */ + ClearanceComputationType clearanceComputationType{NONE}; + + /** \brief Flag indicating that this state validity checker can return + a direction that moves a state away from being invalid. */ + bool hasValidDirectionComputation{false}; + }; + + /** \brief Abstract definition for a class checking the + validity of states. The implementation of this class must + be thread safe. */ + class StateValidityChecker + { + public: + /** \brief Constructor */ + StateValidityChecker(SpaceInformation *si) : si_(si) + { + } + + /** \brief Constructor */ + StateValidityChecker(const SpaceInformationPtr &si) : si_(si.get()) + { + } + + virtual ~StateValidityChecker() = default; + + /** \brief Return true if the state \e state is valid. Usually, this means at least collision checking. If + it is + possible that ompl::base::StateSpace::interpolate() or ompl::control::ControlSpace::propagate() return + states that + are outside of bounds, this function should also make a call to + ompl::base::SpaceInformation::satisfiesBounds(). */ + virtual bool isValid(const State *state) const = 0; + + /** \brief Return true if the state \e state is valid. In addition, set \e dist to the distance to the + * nearest invalid state. */ + virtual bool isValid(const State *state, double &dist) const + { + dist = clearance(state); + return isValid(state); + } + + /** \brief Return true if the state \e state is valid. In addition, set \e dist to the distance to the + nearest + invalid state (using clearance()). If a direction that moves \e state away from being invalid is + available, + a valid state in that direction is also set (\e validState). \e validStateAvailable is set to true if \e + validState + is updated. */ + virtual bool isValid(const State *state, double &dist, State *validState, bool &validStateAvailable) const + { + dist = clearance(state, validState, validStateAvailable); + return isValid(state); + } + + /** \brief Report the distance to the nearest invalid state when starting from \e state. If the distance is + negative, the value of clearance is the penetration depth.*/ + virtual double clearance(const State * /*state*/) const + { + return 0.0; + } + + /** \brief Report the distance to the nearest invalid state when starting from \e state, and if possible, + also specify a valid state \e validState in the direction that moves away from the colliding + state. The \e validStateAvailable flag is set to true if \e validState is updated. */ + virtual double clearance(const State *state, State * /*validState*/, bool &validStateAvailable) const + { + validStateAvailable = false; + return clearance(state); + } + + /** \brief Return the specifications (capabilities of this state validity checker) */ + const StateValidityCheckerSpecs &getSpecs() const + { + return specs_; + } + + /** \brief Checks for equivalence between two Statevaliditycheckers + * */ + virtual bool operator==(const StateValidityChecker &) const + { + return false; + } + bool operator!=(const StateValidityChecker &rhs) const + { + return !(*this == rhs); + } + + protected: + /** \brief The instance of space information this state validity checker operates on */ + SpaceInformation *si_; + + /** \brief The specifications of the state validity checker (its capabilities) */ + StateValidityCheckerSpecs specs_; + }; + + /** \brief The simplest state validity checker: all states are valid */ + class AllValidStateValidityChecker : public StateValidityChecker + { + public: + /** \brief Constructor */ + AllValidStateValidityChecker(SpaceInformation *si) : StateValidityChecker(si) + { + } + + /** \brief Constructor */ + AllValidStateValidityChecker(const SpaceInformationPtr &si) : StateValidityChecker(si) + { + } + + /** \brief Always return true (all states are considered valid) */ + bool isValid(const State * /* state */) const override + { + return true; + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedSpaceInformation.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedSpaceInformation.h new file mode 100644 index 00000000..867d77f3 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedSpaceInformation.h @@ -0,0 +1,140 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2015, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Neil T. Dantam */ + +#ifndef OMPL_BASE_TYPED_SPACE_INFORMATION_ +#define OMPL_BASE_TYPED_SPACE_INFORMATION_ + +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/ScopedState.h" + +namespace ompl +{ + namespace base + { + template + class TypedSpaceInformation : public SpaceInformation + { + public: + /*--- Type Definitions ---*/ + + /** The actual type of the state space */ + using SpaceType = SpaceType_; + + /** The actual type of states in the space. */ + using StateType = typename SpaceType::StateType; + + /** The actual type for a Scoped State. */ + using ScopedStateType = ScopedState; + + /** Shared Pointer to the actual type of the space. */ + using SpacePtr = std::shared_ptr; + + /** Shared pointer to the typed space. */ + using Ptr = std::shared_ptr>; + + /*--- Constructor ---*/ + + /** Construct from shared pointer to the actual space. */ + TypedSpaceInformation(const SpacePtr &space) : SpaceInformation(space) + { + } + + /*--- Space Accessors ---*/ + + /** Get space pointer of the proper type, const. */ + const SpaceType *getTypedStateSpace() const + { + return getStateSpace()->template as(); + } + + /** Get space pointer of the proper type. */ + SpaceType *getTypedStateSpace() + { + return getStateSpace()->template as(); + } + + /*--- State Memory Management ---*/ + + /** Allocate a state of the proper type. */ + StateType *allocTypedState() const + { + return this->allocState()->template as(); + } + + /** Allocate memory for typed states in array */ + void allocTypedStates(std::vector &states) const + { + allocStates(states); + } + + /** Free a state of the proper type. */ + void freeTypedState(StateType *state) const + { + freeState(state); + } + + /** Free typed states in array */ + void freeTypedStates(std::vector &states) const + { + freeStates(states); + } + + /** Copy a state of the proper type. */ + void copyTypedState(StateType *destination, const StateType *source) const + { + copyState(destination, source); + } + + /** Clone a state of the proper type. */ + StateType *cloneTypedState(const StateType *source) const + { + return this->cloneState(source)->template as(); + } + + static StateType *state_as(ompl::base::State *s) + { + return s->template as(); + } + + static const StateType *state_as(const ompl::base::State *s) + { + return s->template as(); + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedStateValidityChecker.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedStateValidityChecker.h new file mode 100644 index 00000000..91b18b54 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedStateValidityChecker.h @@ -0,0 +1,85 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2015, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Neil T. Dantam */ + +#ifndef OMPL_BASE_TYPED_STATE_VALIDITY_CHECKER_ +#define OMPL_BASE_TYPED_STATE_VALIDITY_CHECKER_ + +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/StateValidityChecker.h" +#include "ompl/base/TypedSpaceInformation.h" + +namespace ompl +{ + namespace base + { + template + class TypedStateValidityChecker : public StateValidityChecker + { + public: + using SpaceType = SpaceType_; + using SpaceInformationType = TypedSpaceInformation; + + TypedStateValidityChecker(SpaceInformationType *si) : StateValidityChecker(si) + { + } + + TypedStateValidityChecker(const typename SpaceInformationType::Ptr &si) : StateValidityChecker(si) + { + } + + SpaceInformationType *getTypedSpaceInformation() const + { + return static_cast(si_); + } + + SpaceType *getTypedStateSpace() const + { + return getTypedSpaceInformation()->getTypedStateSpace(); + } + + static typename SpaceType::StateType *state_as(State *s) + { + return SpaceInformationType::state_as(s); + } + + static const typename SpaceType::StateType *state_as(const State *s) + { + return SpaceInformationType::state_as(s); + } + }; + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ValidStateSampler.h new file mode 100644 index 00000000..bdf64208 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ValidStateSampler.h @@ -0,0 +1,138 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_VALID_STATE_SAMPLER_ +#define OMPL_BASE_VALID_STATE_SAMPLER_ + +#include "ompl/base/State.h" +#include "ompl/util/ClassForward.h" +#include "ompl/base/GenericParam.h" +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ValidStateSampler */ + OMPL_CLASS_FORWARD(ValidStateSampler); + /// @endcond + + /** \class ompl::base::ValidStateSamplerPtr + \brief A shared pointer wrapper for ompl::base::ValidStateSampler */ + + /** \brief Abstract definition of a state sampler. */ + class ValidStateSampler + { + public: + // non-copyable + ValidStateSampler(const ValidStateSampler &) = delete; + ValidStateSampler &operator=(const ValidStateSampler &) = delete; + + /** \brief Constructor */ + ValidStateSampler(const SpaceInformation *si); + + virtual ~ValidStateSampler(); + + /** \brief Get the name of the sampler */ + const std::string &getName() const + { + return name_; + } + + /** \brief Set the name of the sampler */ + void setName(const std::string &name) + { + name_ = name; + } + + /** \brief Sample a state. Return false in case of failure */ + virtual bool sample(State *state) = 0; + + /** \brief Sample a state near another, within specified distance. Return false, in case of failure. + \note The memory for \e near must be disjoint from the memory for \e state */ + virtual bool sampleNear(State *state, const State *near, double distance) = 0; + + /** \brief Finding a valid sample usually requires + performing multiple attempts. This call allows setting + the number of such attempts. */ + void setNrAttempts(unsigned int attempts) + { + attempts_ = attempts; + } + + /** \brief Get the number of attempts to be performed by the sampling routine */ + unsigned int getNrAttempts() const + { + return attempts_; + } + + /** \brief Get the parameters for the valid state sampler */ + ParamSet ¶ms() + { + return params_; + } + + /** \brief Get the parameters for the valid state sampler */ + const ParamSet ¶ms() const + { + return params_; + } + + protected: + /** \brief The state space this sampler samples */ + const SpaceInformation *si_; + + /** \brief Number of attempts to find a valid sample */ + unsigned int attempts_; + + /** \brief The name of the sampler */ + std::string name_; + + /** \brief The parameters for this instance of the valid state sampler */ + ParamSet params_; + }; + + /** \brief Definition of a function that can allocate a valid state sampler */ + using ValidStateSamplerAllocator = std::function; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalLazySamples.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalLazySamples.h new file mode 100644 index 00000000..e3b32238 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalLazySamples.h @@ -0,0 +1,190 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOALS_GOAL_LAZY_SAMPLES_ +#define OMPL_BASE_GOALS_GOAL_LAZY_SAMPLES_ + +#include +#include +#include +#include +#include "ompl/base/goals/GoalStates.h" + +namespace ompl +{ + namespace base + { + class GoalLazySamples; + + /** \brief Goal sampling function. Returns false when no further calls should be made to it. + Fills its second argument (the state) with the sampled goal state. This function need not + be thread safe. */ + using GoalSamplingFn = std::function; + + /** \brief Definition of a goal region that can be sampled, + but the sampling process can be slow. This class allows + sampling to happen in a separate thread, and the number of + goals may increase, as the planner is running, in a + thread-safe manner. + + \todo The Python bindings for GoalLazySamples class are still broken. + The OMPL C++ code creates a new thread from which you should be able + to call a python Goal sampling function. Acquiring the right threads + and locks and messing around with the Python Global Interpreter Lock + (GIL) is very tricky. + */ + class GoalLazySamples : public GoalStates + { + public: + /** \brief When new samples are generated and added to the + list of possible samples, a callback can be + called. This type specifies the signature of that callback */ + using NewStateCallbackFn = std::function; + + /** \brief Create a goal region that can be sampled in a + lazy fashion. A function (\e samplerFunc) that + produces samples from that region needs to be passed + to this constructor. The sampling thread is + automatically started if \e autoStart is true. The + sampling function is not called in parallel by + OMPL. Hence, the function is not required to be thread + safe, unless the user issues additional calls in + parallel. The instance of GoalLazySamples remains + thread safe however. + + The function \e samplerFunc returns a truth value. If + the return value is true, further calls to the + function can be made. If the return is false, no more + calls should be made. The function takes two + arguments: the instance of GoalLazySamples making the + call and the state to fill with a goal state. For + every state filled in by \e samplerFunc, + addStateIfDifferent() is called. A state computed by + the sampling thread is added if it is "sufficiently + different" from previously added states. A state is + considered "sufficiently different" if it is at least + \e minDist away from previously added states. */ + GoalLazySamples(const SpaceInformationPtr &si, GoalSamplingFn samplerFunc, bool autoStart = true, + double minDist = std::numeric_limits::epsilon()); + + ~GoalLazySamples() override; + + void sampleGoal(State *st) const override; + + double distanceGoal(const State *st) const override; + + void addState(const State *st) override; + + /** \brief Start the goal sampling thread */ + void startSampling(); + + /** \brief Stop the goal sampling thread */ + void stopSampling(); + + /** \brief Return true if the sampling thread is active */ + bool isSampling() const; + + /** \brief Set the minimum distance that a new state returned by the sampling thread needs to be away from + previously added states, so that it is added to the list of goal states. */ + void setMinNewSampleDistance(double dist) + { + minDist_ = dist; + } + + /** \brief Get the minimum distance that a new state returned by the sampling thread needs to be away from + previously added states, so that it is added to the list of goal states. */ + double getMinNewSampleDistance() const + { + return minDist_; + } + + /** \brief The number of times the sampling function was called and it returned true */ + unsigned int samplingAttemptsCount() const + { + return samplingAttempts_; + } + + /** \brief Set the callback function to be called when a new state is added to the list of possible samples. + This function + is not required to be thread safe, as calls are made one at a time. */ + void setNewStateCallback(const NewStateCallbackFn &callback); + + /** \brief Add a state \e st if it further away that \e minDistance from previously added states. Return + * true if the state was added. */ + bool addStateIfDifferent(const State *st, double minDistance); + + /** \brief Return true if GoalStates::couldSample() is true or if the sampling thread is active, as in this + * case it is possible a sample can be produced at some point. */ + bool couldSample() const override; + + bool hasStates() const override; + const State *getState(unsigned int index) const override; + std::size_t getStateCount() const override; + + void clear() override; + + unsigned int maxSampleCount() const override; + + protected: + /** \brief The function that samples goals by calling \e samplerFunc_ in a separate thread */ + void goalSamplingThread(); + + /** \brief Lock for updating the set of states */ + mutable std::mutex lock_; + + /** \brief Function that produces samples */ + GoalSamplingFn samplerFunc_; + + /** \brief Flag used to notify the sampling thread to terminate sampling */ + bool terminateSamplingThread_; + + /** \brief Additional thread for sampling goal states */ + std::thread *samplingThread_; + + /** \brief The number of times the sampling function was called and it returned true */ + unsigned int samplingAttempts_; + + /** \brief Samples returned by the sampling thread are added to the list of states only if + they are at least minDist_ away from already added samples. */ + double minDist_; + + /** \brief If defined, this function is called when a new state is added to the list of possible samples */ + NewStateCallbackFn callback_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalRegion.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalRegion.h new file mode 100644 index 00000000..39961050 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalRegion.h @@ -0,0 +1,96 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOALS_GOAL_REGION_ +#define OMPL_BASE_GOALS_GOAL_REGION_ + +#include "ompl/base/Goal.h" + +namespace ompl +{ + namespace base + { + /** \brief Definition of a goal region */ + class GoalRegion : public Goal + { + public: + /** \brief Create a goal region */ + GoalRegion(const SpaceInformationPtr &si); + + ~GoalRegion() override = default; + + /** \brief Equivalent to calling isSatisfied(const State *, double *) with a nullptr second argument. */ + bool isSatisfied(const State *st) const override; + + /** \brief Decide whether a given state is part of the + goal region. Returns true if the distance to goal is + less than the threshold (using distanceGoal()) */ + bool isSatisfied(const State *st, double *distance) const override; + + /** \brief Compute the distance to the goal + (heuristic). This function is the one used in + computing the distance to the goal in a call to + isSatisfied() */ + virtual double distanceGoal(const State *st) const = 0; + + /** \brief Print information about the goal data structure + to a stream */ + void print(std::ostream &out = std::cout) const override; + + /** \brief Set the distance to the goal that is allowed + for a state to be considered in the goal region */ + void setThreshold(double threshold) + { + threshold_ = threshold; + } + + /** \brief Get the distance to the goal that is allowed + for a state to be considered in the goal region */ + double getThreshold() const + { + return threshold_; + } + + protected: + /** \brief The maximum distance that is allowed to the + goal. By default, this is initialized to the minimum + epsilon value a double can represent */ + double threshold_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSampleableRegion.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSampleableRegion.h new file mode 100644 index 00000000..944e4e23 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSampleableRegion.h @@ -0,0 +1,83 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOALS_GOAL_SAMPLEABLE_REGION_ +#define OMPL_BASE_GOALS_GOAL_SAMPLEABLE_REGION_ + +#include "ompl/base/goals/GoalRegion.h" + +namespace ompl +{ + namespace base + { + /** \brief Abstract definition of a goal region that can be sampled */ + class GoalSampleableRegion : public GoalRegion + { + public: + /** \brief Create a goal region that can be sampled */ + GoalSampleableRegion(const SpaceInformationPtr &si) : GoalRegion(si) + { + type_ = GOAL_SAMPLEABLE_REGION; + } + + ~GoalSampleableRegion() override = default; + + /** \brief Sample a state in the goal region */ + virtual void sampleGoal(State *st) const = 0; + + /** \brief Return the maximum number of samples that can be asked for before repeating */ + virtual unsigned int maxSampleCount() const = 0; + + /** \brief Return true if maxSampleCount() > 0, since in this case samples can certainly be produced */ + bool canSample() const + { + return maxSampleCount() > 0; + } + + /** \brief Return true if samples could be generated by this sampler at some point in the future. By default + this is equivalent to canSample(), + but for GoalLazySamples, this call also reflects the fact that a sampling thread is active and although no + samples are produced yet, some may + become available at some point in the future. */ + virtual bool couldSample() const + { + return canSample(); + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSpace.h new file mode 100644 index 00000000..2285407e --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSpace.h @@ -0,0 +1,88 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, University of Oxford. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Oxford nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Jonathan Gammell */ + +#ifndef OMPL_BASE_GOALS_GOAL_SPACE_ +#define OMPL_BASE_GOALS_GOAL_SPACE_ + +#include "ompl/base/goals/GoalSampleableRegion.h" +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief Definition of a goal space, i.e., a subspace of the problem state space that defines the goal. */ + class GoalSpace : public GoalSampleableRegion + { + public: + /** \brief Create a goal representation that is a space */ + GoalSpace(const SpaceInformationPtr &si) : GoalSampleableRegion(si) + { + type_ = GOAL_SAMPLEABLE_REGION; + } + + ~GoalSpace() override; + + /** \brief Sample a state in the goal region */ + void sampleGoal(State *st) const override; + + /** \brief Return the maximum number of samples that can be asked for before repeating */ + unsigned int maxSampleCount() const override; + + /** \brief Compute the distance to the goal (heuristic) */ + double distanceGoal(const State *st) const override; + + /** \brief Print information about the goal data structure + to a stream */ + void print(std::ostream &out = std::cout) const override; + + /** \brief Set the goal space */ + void setSpace(const StateSpacePtr space); + + /** \brief Get the goal space */ + StateSpacePtr getSpace() const; + + protected: + /** \brief The goal volume as defined by a state space. */ + StateSpacePtr goalSpace_; + + /** \brief The goal space sampler. */ + StateSamplerPtr goalSampler_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalState.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalState.h new file mode 100644 index 00000000..7a752012 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalState.h @@ -0,0 +1,91 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOALS_GOAL_STATE_ +#define OMPL_BASE_GOALS_GOAL_STATE_ + +#include "ompl/base/goals/GoalSampleableRegion.h" +#include "ompl/base/ScopedState.h" + +namespace ompl +{ + namespace base + { + /** \brief Definition of a goal state */ + class GoalState : public GoalSampleableRegion + { + public: + /** \brief Create a goal representation that is in fact a state */ + GoalState(const SpaceInformationPtr &si) : GoalSampleableRegion(si), state_(nullptr) + { + type_ = GOAL_STATE; + } + + ~GoalState() override; + + /** \brief Sample a state in the goal region */ + void sampleGoal(State *st) const override; + + /** \brief Return the maximum number of samples that can be asked for before repeating */ + unsigned int maxSampleCount() const override; + + /** \brief Compute the distance to the goal (heuristic) */ + virtual double distanceGoal(const State *st) const override; + + /** \brief Print information about the goal data structure + to a stream */ + void print(std::ostream &out = std::cout) const override; + + /** \brief Set the goal state */ + void setState(const State *st); + + /** \brief Set the goal state */ + void setState(const ScopedState<> &st); + + /** \brief Get the goal state */ + const State *getState() const; + + /** \brief Get the goal state */ + State *getState(); + + protected: + /** \brief The goal state */ + State *state_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalStates.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalStates.h new file mode 100644 index 00000000..01c9ed8a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalStates.h @@ -0,0 +1,100 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_GOALS_GOAL_STATES_ +#define OMPL_BASE_GOALS_GOAL_STATES_ + +#include "ompl/base/goals/GoalSampleableRegion.h" +#include "ompl/base/ScopedState.h" +#include + +namespace ompl +{ + namespace base + { + /** \brief Definition of a set of goal states */ + class GoalStates : public GoalSampleableRegion + { + public: + /** \brief Create a goal representation that is in fact a set of states */ + GoalStates(const SpaceInformationPtr &si) : GoalSampleableRegion(si), samplePosition_(0) + { + type_ = GOAL_STATES; + } + + ~GoalStates() override; + + void sampleGoal(State *st) const override; + + unsigned int maxSampleCount() const override; + + double distanceGoal(const State *st) const override; + + void print(std::ostream &out = std::cout) const override; + + /** \brief Add a goal state */ + virtual void addState(const State *st); + + /** \brief Add a goal state (calls the previous definition of addState())*/ + void addState(const ScopedState<> &st); + + /** \brief Clear all goal states */ + virtual void clear(); + + /** \brief Check if there are any states in this goal region */ + virtual bool hasStates() const; + + /** \brief Return a pointer to the indexth state in the state list */ + virtual const State *getState(unsigned int index) const; + + /** \brief Return the number of valid goal states */ + virtual std::size_t getStateCount() const; + + protected: + /** \brief The goal states. Only ones that are valid are considered by the motion planner. */ + std::vector states_; + + private: + /** \brief The index of the next sample to be returned */ + mutable unsigned int samplePosition_; + + /** \brief Free allocated memory */ + void freeMemory(); + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/ControlDurationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/ControlDurationObjective.h new file mode 100644 index 00000000..0cd35fc8 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/ControlDurationObjective.h @@ -0,0 +1,72 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Wolfgang Hönig */ + +#ifndef OMPL_BASE_OBJECTIVES_CONTROL_DURATION_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_CONTROL_DURATION_OPTIMIZATION_OBJECTIVE_ + +#include "ompl/base/OptimizationObjective.h" +#include "ompl/control/SpaceInformation.h" + +namespace ompl +{ + namespace base + { + /** \brief Defines optimization objectives where the total + time of a control action is summed. This cost function is + specified by implementing the controlCost() method. */ + class ControlDurationObjective : public OptimizationObjective + { + public: + /** \brief Requires a control::SpaceInformationPtr to access \p dt. */ + ControlDurationObjective(const control::SpaceInformationPtr &si); + + /** \brief Returns a cost with a value of 0. */ + Cost stateCost(const State *s) const override; + + /** \brief Returns a cost with a value of 0. */ + Cost motionCost(const State *s1, const State *s2) const override; + + /** \brief Returns the cost with the value of steps*dt. */ + Cost controlCost(const control::Control *c, unsigned int steps) const override; + + protected: + /** \brief Duration of each control step. */ + double dt_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MaximizeMinClearanceObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MaximizeMinClearanceObjective.h new file mode 100644 index 00000000..bf1f884c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MaximizeMinClearanceObjective.h @@ -0,0 +1,70 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres */ + +#ifndef OMPL_BASE_OBJECTIVES_MAXIMIZE_MIN_CLEARANCE_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_MAXIMIZE_MIN_CLEARANCE_OBJECTIVE_ + +#include "ompl/base/objectives/MinimaxObjective.h" + +namespace ompl +{ + namespace base + { + /** \brief Objective for attempting to maximize the minimum clearance along a path. */ + class MaximizeMinClearanceObjective : public MinimaxObjective + { + public: + MaximizeMinClearanceObjective(const SpaceInformationPtr &si); + + /** \brief Defined as the clearance of the state \e s, which is computed using the StateValidityChecker in + * this objective's SpaceInformation */ + Cost stateCost(const State *s) const override; + + /** \brief Since we wish to maximize clearance, and costs are equivalent to path clearance, we return the + * greater of the two cost values. */ + bool isCostBetterThan(Cost c1, Cost c2) const override; + + /** \brief Returns +infinity, since any cost combined with +infinity under this objective will always return + * the other cost. */ + Cost identityCost() const override; + + /** \brief Returns -infinity, since no path clearance value can be considered worse than this. */ + Cost infiniteCost() const override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MechanicalWorkOptimizationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MechanicalWorkOptimizationObjective.h new file mode 100644 index 00000000..7926dadb --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MechanicalWorkOptimizationObjective.h @@ -0,0 +1,72 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres */ + +#ifndef OMPL_BASE_OBJECTIVES_MECHANICAL_WORK_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_MECHANICAL_WORK_OPTIMIZATION_OBJECTIVE_ + +#include "ompl/base/OptimizationObjective.h" + +namespace ompl +{ + namespace base + { + /** \brief An optimization objective which defines path cost using the idea of mechanical work. To be used in + * conjunction with TRRT. */ + class MechanicalWorkOptimizationObjective : public OptimizationObjective + { + public: + /** \brief The mechanical work formulation requires a weighing factor to use for the length of a path in + * order to disambiguate optimal paths. This weighing factor should be small. The default value for this + * weight is 0.00001. */ + MechanicalWorkOptimizationObjective(const SpaceInformationPtr &si, double pathLengthWeight = 0.00001); + + /** \brief Set the factor to use for weighing path length in the mechanical work objective formulation. */ + virtual double getPathLengthWeight() const; + + /** \brief Returns a cost with a value of 1. */ + Cost stateCost(const State *s) const override; + + /** \brief Defines motion cost in terms of the mechanical work formulation used for TRRT. */ + Cost motionCost(const State *s1, const State *s2) const override; + + protected: + /** \brief The weighing factor for the path length in the mechanical work objective formulation. */ + double pathLengthWeight_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimaxObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimaxObjective.h new file mode 100644 index 00000000..c59a157e --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimaxObjective.h @@ -0,0 +1,70 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres */ + +#ifndef OMPL_BASE_OBJECTIVES_MINIMAX_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_MINIMAX_OBJECTIVE_ + +#include "ompl/base/OptimizationObjective.h" + +namespace ompl +{ + namespace base + { + /** \brief The cost of a path is defined as the worst state + cost over the entire path. This objective attempts to find + the path with the "best worst cost" over all paths. */ + class MinimaxObjective : public OptimizationObjective + { + public: + MinimaxObjective(const SpaceInformationPtr &si); + + /** \brief Returns a cost with a value of 1. */ + Cost stateCost(const State *s) const override; + + /** \brief Interpolates between \e s1 and \e s2 to check for + state costs along the motion between the two + states. Assumes all costs are worse than identity */ + Cost motionCost(const State *s1, const State *s2) const override; + + /** \brief Since we're only concerned about the "worst" + state cost in the path, combining two costs just + returns the worse of the two. */ + Cost combineCosts(Cost c1, Cost c2) const override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimizeArrivalTime.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimizeArrivalTime.h new file mode 100644 index 00000000..fda44ba5 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimizeArrivalTime.h @@ -0,0 +1,70 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, Technische Universität Berlin (TU Berlin) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the TU Berlin nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Francesco Grothe */ + +#ifndef OMPL_MINIMIZEARRIVALTIME_H +#define OMPL_MINIMIZEARRIVALTIME_H + +#include "ompl/base/OptimizationObjective.h" +#include "ompl/base/spaces/TimeStateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief The cost of a path is defined as the highest time value along its states. This objective attempts to + * optimize for the minimum arrival time. */ + class MinimizeArrivalTime : public OptimizationObjective + { + public: + MinimizeArrivalTime(const SpaceInformationPtr &si); + + private: + /** \brief Return the time value of the state. */ + base::Cost stateCost(const ompl::base::State *s) const override; + + /** \brief Return the cost combination of the two states. */ + base::Cost motionCost(const ompl::base::State *s1, const ompl::base::State *s2) const override; + + /** \brief Return the higher cost. */ + base::Cost combineCosts(ompl::base::Cost c1, ompl::base::Cost c2) const override; + + /** \brief Return negative infinity. */ + base::Cost identityCost() const override; + }; + } // namespace base +} // namespace ompl + +#endif // OMPL_MINIMIZEARRIVALTIME_H diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/PathLengthOptimizationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/PathLengthOptimizationObjective.h new file mode 100644 index 00000000..1a54c3d7 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/PathLengthOptimizationObjective.h @@ -0,0 +1,79 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres, Jonathan Gammell (allocInformedStateSampler) */ + +#ifndef OMPL_BASE_OBJECTIVES_PATH_LENGTH_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_PATH_LENGTH_OPTIMIZATION_OBJECTIVE_ + +#include "ompl/base/OptimizationObjective.h" + +namespace ompl +{ + namespace base + { + /** \brief An optimization objective which corresponds to optimizing path length. */ + class PathLengthOptimizationObjective : public OptimizationObjective + { + public: + PathLengthOptimizationObjective(const SpaceInformationPtr &si); + + /** \brief Returns identity cost. */ + Cost stateCost(const State *s) const override; + + /** \brief Motion cost for this objective is defined as + the configuration space distance between \e s1 and \e + s2, using the method SpaceInformation::distance(). */ + Cost motionCost(const State *s1, const State *s2) const override; + + /** \brief the motion cost heuristic for this objective is + simply the configuration space distance between \e s1 + and \e s2, since this is the optimal cost between any + two states assuming no obstacles. */ + Cost motionCostHeuristic(const State *s1, const State *s2) const override; + + /** \brief the best motion cost estimate for this objective is + simply the configuration space distance between \e s1 + and \e s2, since this is the optimal cost between any + two states assuming no obstacles. */ + Cost motionCostBestEstimate(const State *s1, const State *s2) const override; + + /** \brief Allocate a state sampler for the path-length objective (i.e., direct ellipsoidal sampling). */ + InformedSamplerPtr allocInformedStateSampler(const ProblemDefinitionPtr &probDefn, + unsigned int maxNumberCalls) const override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/StateCostIntegralObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/StateCostIntegralObjective.h new file mode 100644 index 00000000..ee0fae78 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/StateCostIntegralObjective.h @@ -0,0 +1,130 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Luis G. Torres */ + +#ifndef OMPL_BASE_OBJECTIVES_STATE_COST_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_STATE_COST_OPTIMIZATION_OBJECTIVE_ + +#include "ompl/base/OptimizationObjective.h" + +namespace ompl +{ + namespace base + { + /** \brief Defines optimization objectives where path cost can + be represented as a path integral over a cost function + defined over the state space. This cost function is + specified by implementing the stateCost() method. */ + class StateCostIntegralObjective : public OptimizationObjective + { + public: + /** \brief If enableMotionCostInterpolation is set to + true, then calls to motionCost() will divide the + motion segment into smaller parts (the number of parts + being defined by StateSpace::validSegmentCount()) for + more accurate cost integral computation (but this + takes more computation time). If + enableMotionCostInterpolation is false (the default), + only the two endpoint states are used for motion cost + computation. + */ + StateCostIntegralObjective(const SpaceInformationPtr &si, bool enableMotionCostInterpolation = false); + + /** \brief Returns a cost with a value of 1. */ + Cost stateCost(const State *s) const override; + + /** \brief Compute the cost of a path segment from \e s1 to \e s2 (including endpoints) + \param s1 start state of the motion to be evaluated + \param s2 final state of the motion to be evaluated + \param cost the cost of the motion segment + + By default, this function computes + \f{eqnarray*}{ + \mbox{cost} &=& \frac{cost(s_1) + cost(s_2)}{2}\vert s_1 - s_2 \vert + \f} + + If enableMotionCostInterpolation was specified as true + in constructing this object, the cost will be computed + by separating the motion into + StateSpace::validSegmentCount() segments, using the + above formula to compute the cost of each of those + segments, and adding them up. + */ + Cost motionCost(const State *s1, const State *s2) const override; + + /** \brief Estimate the cost of a path segment from \e s1 to \e s2 (including endpoints). + \param s1 start state of the motion to be evaluated + \param s2 final state of the motion to be evaluated + \param cost the cost of the motion segment + + This function computes + \f{eqnarray*}{ + \mbox{cost} &=& \frac{cost(s_1) + cost(s_2)}{2}\vert s_1 - s_2 \vert + \f} + regardless of whether enableMotionCostInterpolation was specified as true in + constructing this object. + */ + Cost motionCostBestEstimate(const State *s1, const State *s2) const override; + + /** \brief Returns whether this objective subdivides + motions into smaller segments for more accurate motion + cost computation. Motion cost interpolation is + disabled by default. + */ + bool isMotionCostInterpolationEnabled() const; + + protected: + /** \brief If true, then motionCost() will more accurately compute + the cost of a motion by taking small steps along the + motion and accumulating the cost. This sacrifices speed + for accuracy. If false, the motion cost will be + approximated by taking the average of the costs at the + two end points, and normalizing by the distance between + the two end points. */ + bool interpolateMotionCost_; + + /** \brief Helper method which uses the trapezoidal rule + to approximate the integral of the cost between two + states of distance \e dist and costs \e c1 and \e + c2 */ + Cost trapezoid(Cost c1, Cost c2, double dist) const + { + return Cost(0.5 * dist * (c1.value() + c2.value())); + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFMechanicalWorkOptimizationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFMechanicalWorkOptimizationObjective.h new file mode 100644 index 00000000..69dbe438 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFMechanicalWorkOptimizationObjective.h @@ -0,0 +1,97 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2015, Caleb Voss and Wilson Beebe + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Caleb Voss, Wilson Beebe */ + +#ifndef OMPL_BASE_OBJECTIVES_VF_MECHANICAL_WORK_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_VF_MECHANICAL_WORK_OPTIMIZATION_OBJECTIVE_ + +#include + +#include "ompl/base/objectives/MechanicalWorkOptimizationObjective.h" +#include "ompl/geometric/planners/rrt/VFRRT.h" + +namespace ompl +{ + namespace base + { + /** + * Optimization objective that computes mechanical work between two states by following a vector field. + */ + class VFMechanicalWorkOptimizationObjective : public ompl::base::MechanicalWorkOptimizationObjective + { + public: + /** Constructor. */ + VFMechanicalWorkOptimizationObjective(const ompl::base::SpaceInformationPtr &si, + geometric::VFRRT::VectorField vf) + : ompl::base::MechanicalWorkOptimizationObjective(si), vf_(std::move(vf)) + { + } + + /** Assume we can always do better. */ + bool isSatisfied(ompl::base::Cost) const override + { + return false; + } + + /** Compute mechanical work between two states. */ + ompl::base::Cost motionCost(const ompl::base::State *s1, const ompl::base::State *s2) const override + { + const base::StateSpacePtr &space = si_->getStateSpace(); + // Per equation 7 in the paper + Eigen::VectorXd f = vf_(s2); + unsigned int vfdim = f.size(); + Eigen::VectorXd qprime(vfdim); + + for (unsigned int i = 0; i < vfdim; i++) + qprime[i] = *space->getValueAddressAtIndex(s2, i) - *space->getValueAddressAtIndex(s1, i); + + // Don't included negative work + double positiveCostAccrued = std::max(-(f.dot(qprime)), 0.); + return ompl::base::Cost(positiveCostAccrued + pathLengthWeight_ * si_->distance(s1, s2)); + } + + bool isSymmetric() const override + { + return false; + } + + protected: + /** VectorField associated with the space. */ + geometric::VFRRT::VectorField vf_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFUpstreamCriterionOptimizationObjective.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFUpstreamCriterionOptimizationObjective.h new file mode 100644 index 00000000..aeedacd7 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFUpstreamCriterionOptimizationObjective.h @@ -0,0 +1,112 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2015, Caleb Voss and Wilson Beebe + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Caleb Voss, Wilson Beebe */ + +#ifndef OMPL_BASE_OBJECTIVES_VF_UPSTREAM_CRITERION_OPTIMIZATION_OBJECTIVE_ +#define OMPL_BASE_OBJECTIVES_VF_UPSTREAM_CRITERION_OPTIMIZATION_OBJECTIVE_ + +#include + +#include "ompl/base/OptimizationObjective.h" +#include "ompl/geometric/planners/rrt/VFRRT.h" + +namespace ompl +{ + namespace base + { + /** + * Optimization objective that computes the upstream criterion between two states. + */ + class VFUpstreamCriterionOptimizationObjective : public ompl::base::OptimizationObjective + { + public: + /** Constructor. */ + VFUpstreamCriterionOptimizationObjective(const ompl::base::SpaceInformationPtr &si, + geometric::VFRRT::VectorField vf) + : ompl::base::OptimizationObjective(si), vf_(std::move(vf)) + { + description_ = "Upstream Criterion"; + } + + /** Assume we can always do better. */ + bool isSatisfied(ompl::base::Cost) const override + { + return false; + } + + /** \brief Returns a cost with a value of 0. */ + Cost stateCost(const State *) const override + { + return Cost(0.); + } + + /** Compute upstream criterion between two states. */ + ompl::base::Cost motionCost(const State *s1, const State *s2) const override + { + const base::StateSpacePtr &space = si_->getStateSpace(); + // Per equation 1 in the paper, Riemann approximation on the left + unsigned int vfdim = space->getValueLocations().size(); + Eigen::VectorXd qprime(vfdim); + unsigned int numSegments = space->validSegmentCount(s1, s2); + std::vector interp; + + for (unsigned int i = 0; i < vfdim; i++) + qprime[i] = *space->getValueAddressAtIndex(s2, i) - *space->getValueAddressAtIndex(s1, i); + qprime.normalize(); + si_->getMotionStates(s1, s2, interp, numSegments - 1, true, true); + double cost = 0; + for (unsigned int i = 0; i < interp.size() - 1; i++) + { + Eigen::VectorXd f = vf_(interp[i]); + cost += si_->distance(interp[i], interp[i + 1]) * (f.norm() - f.dot(qprime)); + si_->freeState(interp[i]); + } + si_->freeState(interp[interp.size() - 1]); + return ompl::base::Cost(cost); + } + + bool isSymmetric() const override + { + return false; + } + + protected: + /** VectorField associated with the space. */ + geometric::VFRRT::VectorField vf_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/BridgeTestValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/BridgeTestValidStateSampler.h new file mode 100644 index 00000000..f3d2a7fb --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/BridgeTestValidStateSampler.h @@ -0,0 +1,95 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, + * National Institute of Advanced Industrial Science and + * Technology (AIST) + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the National Institute of Advanced Industrial + * Science and Technology nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SAMPLERS_BRIDGE_TEST_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_BRIDGE_TEST_VALID_STATE_SAMPLER_ + +#include "ompl/base/StateSampler.h" +#include "ompl/base/ValidStateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief Generate valid samples using bridge test. First + sample an invalid state, then sample another invalid state. Take the midpoint of those samples. + If midpoint is valid, return. If midpoint is invalid continue. + + @par External documentation + Hsu, D., Jiang, T., Reif, J., & Sun, Z., The bridge test for sampling narrow + passages with probabilistic roadmap planners. In Robotics and + Automation, 2003. + [[URL]](http://dx.doi.org/10.1109/ROBOT.2003.1242285) + + */ + + class BridgeTestValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + BridgeTestValidStateSampler(const SpaceInformation *si); + + ~BridgeTestValidStateSampler() override = default; + + bool sample(State *state) override; + bool sampleNear(State *state, const State *near, double distance) override; + + /** \brief Get the standard deviation used when sampling */ + double getStdDev() const + { + return stddev_; + } + + /** \brief Set the standard deviation to use when sampling */ + void setStdDev(double stddev) + { + stddev_ = stddev; + } + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + + /** \brief The standard deviation to use in the sampling process */ + double stddev_; + }; + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ConditionalStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ConditionalStateSampler.h new file mode 100644 index 00000000..60900279 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ConditionalStateSampler.h @@ -0,0 +1,112 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, Technische Universität Berlin (TU Berlin) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the TU Berlin nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Francesco Grothe */ + +#ifndef OMPL_CONDITIONALSTATESAMPLER_H +#define OMPL_CONDITIONALSTATESAMPLER_H + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/SpaceInformation.h" +#include "ompl/base/spaces/SpaceTimeStateSpace.h" + +namespace ompl +{ + namespace base + { + + /** \brief The Conditional Sampler samples feasible Space-Time States. First, a space configuration is + * sampled. Then, a feasible time conditioned on the start and goal states is sampled for the space + * configuration.*/ + class ConditionalStateSampler : public ValidStateSampler + { + public: + /** \brief Representation of a motion */ + class Motion + { + public: + Motion() = default; + + explicit Motion(const SpaceInformationPtr &si) : state(si->allocState()) + { + } + + ~Motion() = default; + + const base::State *root{nullptr}; + base::State *state{nullptr}; + Motion *parent{nullptr}; + /** \brief The set of motions descending from the current motion */ + std::vector children{}; + // only used by goal tree + Motion *connectionPoint{nullptr}; // the start tree motion, if there is a direct connection + int numConnections{0}; // number of connections to the start tree of self and all descendants + }; + + /** \brief The constructor. */ + ConditionalStateSampler(const SpaceInformation *si, Motion *&startMotion, + std::vector &goalMotions, std::vector &newBatchGoalMotions, + bool &sampleOldBatch); + + bool sample(State *state) override; + bool sampleNear(State *state, const State *near, double distance) override; + + private: + /** \brief The internal state sampler, that samples the space (but not time). */ + StateSamplerPtr internalSampler_ = si_->allocStateSampler(); + + /** \brief References to the start state and goal states. */ + Motion *&startMotion_; + + /** \brief The goal motions of the old batch for time conditioning. */ + std::vector &goalMotions_; + + /** \brief The goal motions of the new batch for time conditioning. */ + std::vector &newBatchGoalMotions_; + + /** \brief References to whether the old or new batch region is sampled. */ + bool &sampleOldBatch_; + + /** \brief Maximum tries to sample a new state, if no new state could be sampled, force a new goal + * sample. */ + int maxTries_ = 10; + + /** \brief The random number generator. */ + ompl::RNG rng_; + }; + } // namespace base +} // namespace ompl + +#endif // OMPL_CONDITIONALSTATESAMPLER_H diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/DeterministicStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/DeterministicStateSampler.h new file mode 100644 index 00000000..c09c88cf --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/DeterministicStateSampler.h @@ -0,0 +1,186 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, Robert Bosch GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Robert Bosch GmbH nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Leonard Bruns */ + +#ifndef OMPL_BASE_DETERMINISTIC_STATE_SAMPLER_ +#define OMPL_BASE_DETERMINISTIC_STATE_SAMPLER_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/samplers/deterministic/DeterministicSequence.h" + +#include + +namespace ompl +{ + namespace base + { + /** + @anchor DeterministicStateSampler + @par Short description + \ref DeterministicStateSampler Implementation of a deterministic state sampler. The + implementation allows to load and draw samples from a precomputed sequence or from the Halton Sequence, + @par External documentation + Dispertio: Optimal Sampling For Safe Deterministic Motion Planning + L Palmieri, L Bruns, M Meurer, KO Arras - IEEE Robotics and Automation Letters, 2019 + DOI: [10.1109/LRA.2019.2958525](https://ieeexplore.ieee.org/abstract/document/8928532)
+ [[PDF]](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8928532) + */ + + /** \brief An abstract class for the concept of using deterministic sampling sequences + to decrease the dispersion of the samples. */ + class DeterministicStateSampler : public StateSampler + { + public: + enum DeterministicSamplerType + { + HALTON + }; + + /** \brief Constructor, which creates the sequence internally based on the specified sequence type. + Uses the default constructor for the sequence.*/ + DeterministicStateSampler(const StateSpace *space, + DeterministicSamplerType type = DeterministicSamplerType::HALTON); + /** \brief Constructor that takes a pointer to a DeterministicSequence and uses that object instead + of its own. This can be used to apply non default options to the deterministic sequence.*/ + DeterministicStateSampler(const StateSpace *space, std::shared_ptr sequence_ptr); + + virtual ~DeterministicStateSampler() = default; + + virtual void sampleUniform(State *state) + { + std::vector sample = sequence_ptr_->sample(); + space_->copyFromReals(state, sample); + return; + } + + virtual void sampleUniformNear(State *, const State *, double) + { + OMPL_ERROR("sampleUniformNear is not supported for DeterministicStateSampler"); + } + virtual void sampleGaussian(State *, const State *, double) + { + OMPL_ERROR("sampleGaussian is not supported for DeterministicStateSampler"); + } + + protected: + std::shared_ptr sequence_ptr_; + }; + + /** \brief Deterministic state space sampler for SO(2) */ + class SO2DeterministicStateSampler : public DeterministicStateSampler + { + public: + /** \brief Constructor, which creates the sequence internally based on the specified sequence type. + Uses the default constructor for the sequence.*/ + SO2DeterministicStateSampler(const StateSpace *space, + DeterministicSamplerType type = DeterministicSamplerType::HALTON) + : DeterministicStateSampler(space, type) + { + } + /** \brief Constructor that takes a pointer to a DeterministicSequence and uses that object instead + of its own. This can be used to apply non default options to the deterministic sequence.*/ + SO2DeterministicStateSampler(const StateSpace *space, std::shared_ptr sequence_ptr) + : DeterministicStateSampler(space, sequence_ptr) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief Deterministic state sampler for the Rn state space */ + class RealVectorDeterministicStateSampler : public DeterministicStateSampler + { + public: + /** \brief Constructor, which creates the sequence internally based on the specified sequence type. + Uses the default constructor for the sequence.*/ + RealVectorDeterministicStateSampler(const StateSpace *space, + DeterministicSamplerType type = DeterministicSamplerType::HALTON) + : DeterministicStateSampler(space, type), stretch_(true) + { + } + /** \brief Constructor that takes a pointer to a DeterministicSequence and uses that object instead + of its own. This can be used to apply non default options to the deterministic sequence.*/ + RealVectorDeterministicStateSampler(const StateSpace *space, + std::shared_ptr sequence_ptr, + bool stretch = true) + : DeterministicStateSampler(space, sequence_ptr), stretch_(stretch) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + private: + bool stretch_{false}; // indicates whether the state is samples in [0,1] and should be stretched to the + // state space boundaries + }; + + /** \brief Deterministic state sampler for the Rn state space */ + class SE2DeterministicStateSampler : public DeterministicStateSampler + { + public: + /** \brief Constructor, which creates the sequence internally based on the specified sequence type. + Uses the default constructor for the sequence.*/ + SE2DeterministicStateSampler(const StateSpace *space, + DeterministicSamplerType type = DeterministicSamplerType::HALTON) + : DeterministicStateSampler(space, type), stretch_rv_(true), stretch_so2_(true) + { + } + /** \brief Constructor that takes a pointer to a DeterministicSequence and uses that object instead + of its own. This can be used to apply non default options to the deterministic sequence.*/ + SE2DeterministicStateSampler(const StateSpace *space, std::shared_ptr sequence_ptr, + bool stretch_rv = true, bool stretch_so2 = true) + : DeterministicStateSampler(space, sequence_ptr), stretch_rv_(stretch_rv), stretch_so2_(stretch_so2) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + private: + bool stretch_rv_; // indicates whether the xy state is sampled in [0,1] and should be stretched to the + // state space boundaries + bool stretch_so2_; // indicates whether the so2 state is sampled in [0,1] and should be stretched to + // [-pi;pi] + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/GaussianValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/GaussianValidStateSampler.h new file mode 100644 index 00000000..6b4edae7 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/GaussianValidStateSampler.h @@ -0,0 +1,81 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SAMPLERS_GAUSSIAN_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_GAUSSIAN_VALID_STATE_SAMPLER_ + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief Generate valid samples using the Gaussian sampling strategy */ + class GaussianValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + GaussianValidStateSampler(const SpaceInformation *si); + + ~GaussianValidStateSampler() override = default; + + bool sample(State *state) override; + bool sampleNear(State *state, const State *near, double distance) override; + + /** \brief Get the standard deviation used when sampling */ + double getStdDev() const + { + return stddev_; + } + + /** \brief Set the standard deviation to use when sampling */ + void setStdDev(double stddev) + { + stddev_ = stddev; + } + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + + /** \brief The standard deviation to use in the sampling process */ + double stddev_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/InformedStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/InformedStateSampler.h new file mode 100644 index 00000000..870f7fac --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/InformedStateSampler.h @@ -0,0 +1,171 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, University of Toronto + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Toronto nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Jonathan Gammell */ + +#ifndef OMPL_BASE_SAMPLERS_INFORMED_SAMPLER_ +#define OMPL_BASE_SAMPLERS_INFORMED_SAMPLER_ + +// We inherit from StateSampler +#include "ompl/base/StateSampler.h" +// Deriving functions must be able to sample within a given cost +#include "ompl/base/Cost.h" +// We use a pointer to the problem definition to access problem and solution data. +#include "ompl/base/ProblemDefinition.h" + +// For std::function +#include + +namespace ompl +{ + namespace base + { + OMPL_CLASS_FORWARD(InformedSampler); + OMPL_CLASS_FORWARD(InformedStateSampler); + + /** \brief An abstract class for the concept of using information about the state space + and the current solution cost to limit future search to a planning + subproblem that contains all possibly better solutions. */ + class InformedSampler + { + public: + // non-copyable + InformedSampler(const InformedSampler &) = delete; + InformedSampler &operator=(const InformedSampler &) = delete; + + /** \brief Construct a sampler that only generates states with a heuristic solution estimate that is less + than the cost of the current solution. Requires a function pointer to a method to query the cost of the + current solution. + If iteration is required, only maxNumberCalls are attempted, to assure that the function returns. */ + InformedSampler(const ProblemDefinitionPtr &probDefn, unsigned int maxNumberCalls); + + virtual ~InformedSampler() = default; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost, i.e. in the interval [0, maxCost). Returns false if such a state was not found in + * the specified number of iterations. */ + virtual bool sampleUniform(State *statePtr, const Cost &maxCost) = 0; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are between + * the provided costs, [minCost, maxCost). Returns false if such a state was not found in the specified + * number of iterations. */ + virtual bool sampleUniform(State *statePtr, const Cost &minCost, const Cost &maxCost) = 0; + + /** \brief Whether the sampler can provide a measure of the informed subset */ + virtual bool hasInformedMeasure() const = 0; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. Does not consider problem boundaries but returns the measure of the entire space if no solution + * has been found or if a closed form expression for the measure does not exist. */ + virtual double getInformedMeasure(const Cost ¤tCost) const = 0; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. Does not consider problem boundaries but returns the measure of the entire space if no solution + * has been found or if a closed form expression for the measure does not exist. By default calls the + * 1-argument overloaded version with the min and max costs and subtracts the differences; however, there + * may be more efficient ways to do this for some cost functions. */ + virtual double getInformedMeasure(const Cost &minCost, const Cost &maxCost) const; + + /** \brief A helper function to calculate the heuristic estimate of the solution cost for a given state + * using the optimization objective stored in the problem definition. */ + /** \todo With the future invention of a heuristic class, this should move. */ + virtual Cost heuristicSolnCost(const State *statePtr) const; + + /** Helper for the OrderedInfSampler wrapper */ + ProblemDefinitionPtr getProblemDefn() const; + + /** Helper for the OrderedInfSampler wrapper */ + unsigned int getMaxNumberOfIters() const; + + protected: + /** \brief A copy of the problem definition */ + ProblemDefinitionPtr probDefn_; + /** \brief A copy of the optimization objective */ + OptimizationObjectivePtr opt_; + /** \brief A copy of the state space*/ + StateSpacePtr space_; + /** \brief The number of iterations I'm allowed to attempt */ + unsigned int numIters_; + }; + + /** \brief A wrapper class that allows an InformedSampler to be used as a StateSampler. */ + class InformedStateSampler : public StateSampler + { + public: + /** \brief The definition of a function pointer for querying the current solution cost. */ + using GetCurrentCostFunc = std::function; + + /** \brief Construct a sampler that only generates states with a heuristic solution estimate that is less + * than the cost of the current solution using the default informed sampler for the current optimization + * objective. Requires a function pointer to a method to query the cost of the current solution. */ + InformedStateSampler(const ProblemDefinitionPtr &probDefn, unsigned int maxNumberCalls, + const GetCurrentCostFunc &costFunc); + + /** \brief Construct a sampler that only generates states with a heuristic solution estimate that is less + * than the cost of the current solution using the provided informed sampler. Requires a function pointer to + * a method to query the cost of the current solution. */ + InformedStateSampler(const ProblemDefinitionPtr &probDefn, const GetCurrentCostFunc &costFunc, + const InformedSamplerPtr &infSampler); + + ~InformedStateSampler() override = default; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the current best cost (as defined by the pointer passed at construction). By default just calls + * sampleUniform(State*, Cost) with cost given by the member variable. */ + void sampleUniform(State *statePtr) override; + + /** \brief By default sampleUniformNear throws. This can be overloaded by a specific informed sampler if + * desired. */ + void sampleUniformNear(State *statePtr, const State *near, double distance) override; + + /** \brief By default sampleGaussian throws. This can be overloaded by a specific informed sampler if + * desired. */ + void sampleGaussian(State *statePtr, const State *mean, double stdDev) override; + + private: + /** \brief A helper function for construction */ + void commonConstructor(const GetCurrentCostFunc &costFunc, const InformedSamplerPtr &infSampler); + + /** \brief A function pointer to a method for querying the best cost found so far. This is the mechanism + * through which the sampler gets "informed" about the current solution. */ + GetCurrentCostFunc bestCostFunc_; + /** \brief A basic sampler */ + StateSamplerPtr baseSampler_; + /** \brief The wrapped informed sampler */ + InformedSamplerPtr infSampler_; + }; + } // namespace base +} // namespace ompl + +#endif // OMPL_BASE_SAMPLERS_INFORMED_SAMPLER_ diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MaximizeClearanceValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MaximizeClearanceValidStateSampler.h new file mode 100644 index 00000000..ce9bfca6 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MaximizeClearanceValidStateSampler.h @@ -0,0 +1,86 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SAMPLERS_MAXIMIZE_CLEARANCE_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_MAXIMIZE_CLEARANCE_VALID_STATE_SAMPLER_ + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief Generate valid samples randomly, but with a bias towards higher clearance. */ + class MaximizeClearanceValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + MaximizeClearanceValidStateSampler(const SpaceInformation *si); + + ~MaximizeClearanceValidStateSampler() override; + + bool sample(State *state) override; + + bool sampleNear(State *state, const State *near, double distance) override; + + /** \brief The number of attempts at improving the clearance of the sampled state. */ + void setNrImproveAttempts(unsigned int attempts) + { + improveAttempts_ = attempts; + } + + /** \brief Get the number of attempts to improve a sampled state */ + unsigned int getNrImproveAttempts() const + { + return improveAttempts_; + } + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + + /** \brief Number of attempts to improve a valid sample */ + unsigned int improveAttempts_; + + private: + /** \brief Temporary work area */ + State *work_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MinimumClearanceValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MinimumClearanceValidStateSampler.h new file mode 100644 index 00000000..ae05f073 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MinimumClearanceValidStateSampler.h @@ -0,0 +1,90 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2016, University of Colorado, Boulder + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Univ of CO, Boulder nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Dave Coleman + Desc: Find a valid sample with a minimum distance to nearby obstacles + (clearance threshold) +*/ + +#ifndef OMPL_BASE_SAMPLERS_MINIMUM_CLEARANCE_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_MINIMUM_CLEARANCE_VALID_STATE_SAMPLER_ + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(MinimumClearanceValidStateSampler); + /// @endcond + + /** \brief Generate valid samples randomly with extra requirement of min for clearance to nearest obstacle */ + class MinimumClearanceValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + MinimumClearanceValidStateSampler(const SpaceInformation *si); + + ~MinimumClearanceValidStateSampler() override = default; + ; + + bool sample(State *state) override; + + bool sampleNear(State *state, const State *near, double distance) override; + + /** \brief Set the minimum required distance of sample from nearest obstacle to be considered valid */ + void setMinimumObstacleClearance(double clearance) + { + clearance_ = clearance; + } + + /** \brief Get the minimum required distance of sample from nearest obstacle to be considered valid */ + double getMinimumObstacleClearance() const + { + return clearance_; + } + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + + /** \brief Minimum required distance of sample from nearest obstacle to be considered valid */ + double clearance_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ObstacleBasedValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ObstacleBasedValidStateSampler.h new file mode 100644 index 00000000..327fd833 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ObstacleBasedValidStateSampler.h @@ -0,0 +1,75 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SAMPLERS_OBSTACLE_BASED_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_OBSTACLE_BASED_VALID_STATE_SAMPLER_ + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief Generate valid samples using obstacle based sampling. First + sample an invalid state, then sample a valid state. Then, interpolate from + the invalid state to the valid state, returning the first valid state + encountered. + + @par External documentation + N. M. Amato, O. B. Bayazit, L. K. Dale, C. Jones, and D. Vallejo, OBPRM: an obstacle-based PRM for 3D + workspaces, in Third Workshop on the Algorithmic Foundations of Robotics, pp. 155-168, 1998. + [[URL]](https://parasol.tamu.edu/groups/amatogroup/research/OBPRM/) + */ + class ObstacleBasedValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + ObstacleBasedValidStateSampler(const SpaceInformation *si); + + ~ObstacleBasedValidStateSampler() override = default; + + bool sample(State *state) override; + bool sampleNear(State *state, const State *near, double distance) override; + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/UniformValidStateSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/UniformValidStateSampler.h new file mode 100644 index 00000000..953d934c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/UniformValidStateSampler.h @@ -0,0 +1,66 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SAMPLERS_UNIFORM_VALID_STATE_SAMPLER_ +#define OMPL_BASE_SAMPLERS_UNIFORM_VALID_STATE_SAMPLER_ + +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/StateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief A state sampler that only samples valid states, uniformly. */ + class UniformValidStateSampler : public ValidStateSampler + { + public: + /** \brief Constructor */ + UniformValidStateSampler(const SpaceInformation *si); + + ~UniformValidStateSampler() override = default; + + bool sample(State *state) override; + bool sampleNear(State *state, const State *near, double distance) override; + + protected: + /** \brief The sampler to build upon */ + StateSamplerPtr sampler_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/DeterministicSequence.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/DeterministicSequence.h new file mode 100644 index 00000000..f52a7a8f --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/DeterministicSequence.h @@ -0,0 +1,64 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, Robert Bosch GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Robert Bosch GmbH nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Leonard Bruns */ + +#ifndef OMPL_BASE_DETERMINISTIC_SEQUENCE +#define OMPL_BASE_DETERMINISTIC_SEQUENCE + +#include + +namespace ompl +{ + namespace base + { + /** \brief An abstract class for deterministic sequences in arbitrary dimensions. */ + class DeterministicSequence + { + public: + /** \brief Constructor */ + DeterministicSequence(unsigned int dimensions) : dimensions_(dimensions) + { + } + virtual ~DeterministicSequence() = default; + + /** \brief Returns the next sample in the interval [0,1] */ + virtual std::vector sample() = 0; + + const unsigned int dimensions_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/HaltonSequence.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/HaltonSequence.h new file mode 100644 index 00000000..317b6621 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/HaltonSequence.h @@ -0,0 +1,104 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, Robert Bosch GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Robert Bosch GmbH nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Leonard Bruns */ + +#ifndef OMPL_BASE_HALTON_SEQUENCE +#define OMPL_BASE_HALTON_SEQUENCE + +#include "ompl/base/samplers/deterministic/DeterministicSequence.h" + +namespace ompl +{ + namespace base + { + /** + @anchor HaltonSequence1D + @par Short description + \ref HaltonSequence1D Realization of the Halton sequence for the generation of + arbitrary dimensional, low-dispersion sequences. + @par External documentation + Implementation follows https://en.wikipedia.org/wiki/Halton_sequence. + A more efficient implementation might be found in + Struckmeier, Jens. "Fast generation of low-discrepancy sequences." Journal of Computational and + Applied Mathematics 61.1 (1995): 29-41. + \brief Realization of the Halton sequence for the generation of + arbitrary dimensional, low-dispersion sequences. + */ + + class HaltonSequence1D + { + public: + /** \brief Constructor */ + HaltonSequence1D(); + + /** \brief Constructor */ + HaltonSequence1D(unsigned int base); + + /** \brief Sets the base of the halton sequence */ + void setBase(unsigned int base); + + /** \brief Returns the next sample in the interval [0,1] */ + double sample(); + + private: + unsigned int i_, base_; + }; + + /** \brief Realization of the Halton sequence for the generation of + arbitrary dimensional, low-dispersion sequences. */ + class HaltonSequence : public DeterministicSequence + { + public: + /** \brief Constructor, only specifiying the dimensions, first n primes will be used + as bases. */ + HaltonSequence(unsigned int dimensions); + /** \brief Constructor, for which the bases vector will be used to initialize the + bases of the 1D halton sequences. bases.size() has to be equal to dimensions. */ + HaltonSequence(unsigned int dimensions, std::vector bases); + + /** \brief Returns the next sample in the interval [0,1] */ + std::vector sample() override; + + private: + std::vector halton_sequences_1d_; + + /** \brief Sets the bases of the 1D Halton generators to the first n primes */ + void setBasesToPrimes(); + }; + } // namespace base + +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/PrecomputedSequence.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/PrecomputedSequence.h new file mode 100644 index 00000000..3ec6cb5c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/PrecomputedSequence.h @@ -0,0 +1,79 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, Robert Bosch GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Robert Bosch GmbH nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Leonard Bruns */ + +#ifndef OMPL_BASE_PRECOMPUTED_SEQUENCE +#define OMPL_BASE_PRECOMPUTED_SEQUENCE + +#include "ompl/base/samplers/deterministic/DeterministicSequence.h" +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief General realization for a sampler of precomputed sequences or sets. */ + class PrecomputedSequence : public DeterministicSequence + { + public: + /** \brief Constructor, requires the path of file containing the precomputed samples + formated with one sample per line, with the dimensions separated by whitespace. Optionally the order of + the samples can be randomized (which removes deterministim, if not all samples are used), max_samples + optionally limits the number of samples to be read from the file (default 0 means all samples are read), + scale_factor optinonally scales the the samples (if the precomputed samplesets are e.g. in range 0,1. **/ + PrecomputedSequence(std::string path, unsigned int dimensions, bool shuffle = false, + size_t max_samples = 0); + + /** \brief Returns the next sample, loops if there are no more precomputed samples. The range + of the samples depends on the precomputed set of samples. */ + std::vector sample() override; + + private: + std::vector> sample_set_; + size_t current_index_{0}; + std::default_random_engine rand_eng_; + + /** \brief Reads a specified number of samples of specified dimension from a specified file. */ + void readSamplesFromFile(std::string path, unsigned int dimensions, size_t max_samples = 0); + + /** \brief Randomly shuffles the set of samples **/ + void shuffleSamples(); + }; + } // namespace base + +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/OrderedInfSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/OrderedInfSampler.h new file mode 100644 index 00000000..55257037 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/OrderedInfSampler.h @@ -0,0 +1,106 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, University of Toronto + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Toronto nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Jonathan Gammell */ + +#ifndef OMPL_BASE_SAMPLERS_INFORMED_ORDERED_INFORMED_SAMPLER_ +#define OMPL_BASE_SAMPLERS_INFORMED_ORDERED_INFORMED_SAMPLER_ + +// We inherit from InformedStateSampler +#include "ompl/base/samplers/InformedStateSampler.h" + +// For a priority queue +#include +// For std::function +#include + +namespace ompl +{ + namespace base + { + /** \brief An informed sampler wrapper that generates \e m samples and then returns them in order of the + heuristic. + + */ + class OrderedInfSampler : public InformedSampler + { + public: + /** \brief Construct an ordering wrapper around the provided informed sampler. */ + OrderedInfSampler(const InformedSamplerPtr &infSamplerPtr, unsigned int batchSize); + ~OrderedInfSampler() override = default; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost, i.e. in the interval [0, maxCost). Returns false if such a state was not found in + * the specified number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &maxCost) override; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are between + * the provided costs, [minCost, maxCost). Returns false if such a state was not found in the specified + * number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &minCost, const Cost &maxCost) override; + + /** \brief Whether the wrapped sampler can provide a measure of the informed subset */ + bool hasInformedMeasure() const override; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. Passes through to the wrapper sampler. */ + double getInformedMeasure(const Cost ¤tCost) const override; + + private: + // Variables + /** \brief The informed sampler to use. */ + InformedSamplerPtr infSampler_; + /** \brief The batch size to use. */ + unsigned int batchSize_; + /** \brief The container of ordered samples. */ + std::priority_queue, std::function> + orderedSamples_; + + // Functions + /** \brief The ordering function for the priority queue */ + bool queueComparator(const State *a, const State *b); + + /** \brief Construct a batch of samples to return with costs in the interval [0, maxCost) */ + void createBatch(const Cost &maxCost); + + /** \brief Construct a batch of samples to return with costs in the interval [minCost, maxCost) */ + void createBatch(const Cost &minCost, const Cost &maxCost); + + /** \brief Clear a batch of prepared samples */ + void clearBatch(); + }; + } // namespace base +} // namespace ompl + +#endif // OMPL_BASE_SAMPLERS_INFORMED_REJECTION_INFORMED_SAMPLER_ diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/PathLengthDirectInfSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/PathLengthDirectInfSampler.h new file mode 100644 index 00000000..de6c120a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/PathLengthDirectInfSampler.h @@ -0,0 +1,194 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, University of Toronto + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Toronto nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Jonathan Gammell */ + +#ifndef OMPL_BASE_SAMPLERS_INFORMED_PATH_LENGTH_DIRECT_INFORMED_SAMPLER_ +#define OMPL_BASE_SAMPLERS_INFORMED_PATH_LENGTH_DIRECT_INFORMED_SAMPLER_ + +// We inherit from InformedStateSampler +#include "ompl/base/samplers/InformedStateSampler.h" + +// For std::list +#include + +namespace ompl +{ + namespace base + { + /** + @anchor gPathLengthDirectInfSampler + + PathLengthDirectInfSampler is a method to generate uniform samples in the subset of a problem that could + provide a shorter path from start to goal. + This subset is a prolate hyperspheroid (PHS), a special type of an hyperellipsoid) and can be sampled + directly. + + Informed sampling is a method to focus search which continuing to consider all homotopy classes that can + provide a better solution. + Directly sampling the informed subset guarantees a non-zero probability of improving a solution regardless + of the size of the planning domain, + the number of state dimensions, and how close the current solution is to the theoretical minimum. + + Currently only implemented for problems in R^n (i.e., RealVectorStateSpace), SE(2) (i.e., SE2StateSpace), + and SE(3) (i.e., SE3StateSpace). + Until an initial solution is found, this sampler simply passes-through to a uniform distribution over the + entire state space. + + @par Associated publication: + + J. D. Gammell, T. D. Barfoot, S. S. Srinivasa, "Informed sampling for asymptotically optimal path planning." + IEEE Transactions on Robotics (T-RO), 34(4): 966-984, Aug. 2018. + DOI: TRO.2018.2830331. + arXiv: 1706.06454 [cs.RO]. + Illustration video. + Short description video. + */ + + /** \brief An informed sampler for problems seeking to minimize path length.*/ + class PathLengthDirectInfSampler : public InformedSampler + { + public: + /** \brief Construct a sampler that only generates states with a heuristic solution estimate that is less + * than the cost of the current solution using a direct ellipsoidal method. */ + PathLengthDirectInfSampler(const ProblemDefinitionPtr &probDefn, unsigned int maxNumberCalls); + ~PathLengthDirectInfSampler() override; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost, i.e. in the interval [0, maxCost). Returns false if such a state was not found in + * the specified number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &maxCost) override; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are between + * the provided costs, [minCost, maxCost). Returns false if such a state was not found in the specified + * number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &minCost, const Cost &maxCost) override; + + /** \brief Whether the sampler can provide a measure of the informed subset */ + bool hasInformedMeasure() const override; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. Does not consider problem boundaries but returns the measure of the entire space if no solution + * has been found. In the case of multiple goals, this measure assume each individual subset is independent, + * therefore the resulting measure will be an overestimate if any of the subsets overlap. */ + double getInformedMeasure(const Cost ¤tCost) const override; + + /** \brief A helper function to calculate the heuristic estimate of the solution cost for the informed + * subset of a given state. */ + Cost heuristicSolnCost(const State *statePtr) const override; + + private: + /** \brief A constant pointer to ProlateHyperspheroid */ + using ProlateHyperspheroidCPtr = std::shared_ptr; + + // Helper functions: + // High level + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost using a persistent iteration counter */ + bool sampleUniform(State *statePtr, const Cost &maxCost, unsigned int *iters); + + /** \brief Sample from the bounds of the problem and keep the sample if it passes the given test. Meant to + * be used with isInAnyPhs and phsPtr->isInPhs() */ + bool sampleBoundsRejectPhs(State *statePtr, unsigned int *iters); + + /** \brief Sample from the given PHS and return true if the sample is within the boundaries of the problem + * (i.e., it \e may be kept). */ + bool samplePhsRejectBounds(State *statePtr, unsigned int *iters); + + // Low level + /** \brief Extract the informed subspace from a state pointer */ + std::vector getInformedSubstate(const State *statePtr) const; + + /** \brief Create a full vector with any uninformed subspaces filled with a uniform random state. Expects + * the state* to be allocated */ + void createFullState(State *statePtr, const std::vector &informedVector); + + /** \brief Iterate through the list of PHSs and update each one to the new max cost as well as the sum of + * their measures. Will remove any PHSs that cannot improve a better solution and in that case update the + * number of goals. */ + void updatePhsDefinitions(const Cost &maxCost); + + /** \brief Select a random PHS from the list of PHSs. The probability of sampling chosing a PHS is it's + * measure relative to the total measure of all PHSs. Bypasses if only one PHS exists. */ + ompl::ProlateHyperspheroidPtr randomPhsPtr(); + + /** \brief Probabilistically decide whether to keep a given sample drawn directly from a PHS. If a sample is + * in K PHSs, it returns true with probability 1/K. */ + bool keepSample(const std::vector &informedVector); + + /** \brief Iterate through the list of PHSs and return true if the sample is in any of them */ + bool isInAnyPhs(const std::vector &informedVector) const; + + /** \brief Return true if the sample is in the specified PHS. */ + bool isInPhs(const ProlateHyperspheroidCPtr &phsCPtr, const std::vector &informedVector) const; + + /** \brief Iterate through the list of PHSs and return the number of PHSs that the sample is in */ + unsigned int numberOfPhsInclusions(const std::vector &informedVector) const; + + // Variables + /** \brief The prolate hyperspheroid description of the sub problems. One per goal state. */ + std::list listPhsPtrs_; + + /** \brief The summed measure of all the start-goal pairs */ + double summedMeasure_; + + /** \brief The index of the subspace of a compound StateSpace for which we can do informed sampling. Unused + * if the StateSpace is not compound. */ + unsigned int informedIdx_; + + /** \brief The state space of the planning problem that is informed by the heuristics, i.e., in SE(2), R^2*/ + StateSpacePtr informedSubSpace_; + + /** \brief The index of the subspace of a compound StateSpace for which we cannot do informed sampling. + * Unused if the StateSpace is not compound. */ + unsigned int uninformedIdx_; + + /** \brief The state space of the planning problem that is \e not informed by the heuristics, i.e., in + * SE(2), SO(2)*/ + StateSpacePtr uninformedSubSpace_; + + /** \brief A regular sampler for the entire statespace for cases where informed sampling cannot be used or + * is not helpful. I.e., Before a solution is found, or if the solution does not reduce the search space. */ + StateSamplerPtr baseSampler_; + + /** \brief A regular sampler to use on the uninformed subspace. */ + StateSamplerPtr uninformedSubSampler_; + + /** \brief An instance of a random number generator */ + RNG rng_; + }; // PathLengthDirectInfSampler + } // namespace base +} // namespace ompl + +#endif // OMPL_BASE_SAMPLERS_INFORMED_DIRECT_PATH_LENGTH_INFORMED_SAMPLER_ diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/RejectionInfSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/RejectionInfSampler.h new file mode 100644 index 00000000..a57129e8 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/RejectionInfSampler.h @@ -0,0 +1,96 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, University of Toronto + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Toronto nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Authors: Jonathan Gammell */ + +#ifndef OMPL_BASE_SAMPLERS_INFORMED_GENERAL_REJECTION_INFORMED_SAMPLER_ +#define OMPL_BASE_SAMPLERS_INFORMED_GENERAL_REJECTION_INFORMED_SAMPLER_ + +// We inherit from InformedStateSampler +#include "ompl/base/samplers/InformedStateSampler.h" + +namespace ompl +{ + namespace base + { + /** \brief A default rejection sampling scheme that samples uniformly from the entire planning domain. + Samples are rejected until one is found that has a heuristic solution estimate that is less than the current + solution. + In general, direct sampling of the informed subset is much better, but this is a general default. + + */ + class RejectionInfSampler : public InformedSampler + { + public: + /** \brief Construct a rejection sampler that only generates states with a heuristic solution estimate that + * is less than the cost of the current solution. */ + RejectionInfSampler(const ProblemDefinitionPtr &probDefn, unsigned int maxNumberCalls); + ~RejectionInfSampler() override = default; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost, i.e. in the interval [0, maxCost). Returns false if such a state was not found in + * the specified number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &maxCost) override; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are between + * the provided costs, [minCost, maxCost). Returns false if such a state was not found in the specified + * number of iterations. */ + bool sampleUniform(State *statePtr, const Cost &minCost, const Cost &maxCost) override; + + /** \brief Whether the sampler can provide a measure of the informed subset */ + bool hasInformedMeasure() const override; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. As rejection sampling has no closed-form knowledge of the informed subset, the measure of the + * informed space is always the measure of the entire space. */ + double getInformedMeasure(const Cost & /*currentCost*/) const override; + + /** \brief The measure of the subset of the state space defined by the current solution cost that is being + * searched. As rejection sampling has no closed-form knowledge of the informed subset, the measure of the + * informed space is always the measure of the entire space. */ + double getInformedMeasure(const Cost & /*minCost*/, const Cost & /*maxCost*/) const override; + + private: + // Variables + /** \brief The basic raw sampler used to generate samples to keep/reject. */ + StateSamplerPtr baseSampler_; + + /** \brief Sample uniformly in the subset of the state space whose heuristic solution estimates are less + * than the provided cost using a persistent iteration counter */ + bool sampleUniform(State *statePtr, const Cost &maxCost, unsigned int *iterPtr); + }; + } // namespace base +} // namespace ompl + +#endif // OMPL_BASE_SAMPLERS_INFORMED_REJECTION_INFORMED_SAMPLER_ diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DiscreteStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DiscreteStateSpace.h new file mode 100644 index 00000000..1a9d2391 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DiscreteStateSpace.h @@ -0,0 +1,164 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Elizabeth Fudge */ + +#ifndef OMPL_BASE_SPACES_DISCRETE_STATE_SPACE_ +#define OMPL_BASE_SPACES_DISCRETE_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for discrete states */ + class DiscreteStateSampler : public StateSampler + { + public: + /** \brief Constructor */ + DiscreteStateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A space representing discrete states; i.e. there + are a small number of discrete states the system can be in. + States are represented as integers [lowerBound, upperBound], + where lowerBound and upperBound are inclusive. + States do not wrap around; i.e. the distance between state + lowerBound and state upperBound is upperBound-lowerBound. + The dimension of the space is 1. */ + class DiscreteStateSpace : public StateSpace + { + public: + /** \brief The definition of a discrete state */ + class StateType : public State + { + public: + /** \brief The current state - an int in range [lowerBound, upperBound] */ + int value; + }; + + /** \brief Construct a discrete space in wich states can take values in the set [\e lowerBound, \e + * upperBound] */ + DiscreteStateSpace(int lowerBound, int upperBound) : lowerBound_(lowerBound), upperBound_(upperBound) + { + setName("Discrete" + getName()); + type_ = STATE_SPACE_DISCRETE; + } + + ~DiscreteStateSpace() override = default; + + bool isDiscrete() const override; + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + void copyState(State *destination, const State *source) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void registerProjections() override; + + /** \brief Returns the number of states possible */ + unsigned int getStateCount() const + { + return upperBound_ - lowerBound_ + 1; + } + + /** \brief Returns the lowest possible state */ + int getLowerBound() const + { + return lowerBound_; + } + + /** \brief Returns the highest possible state */ + int getUpperBound() const + { + return upperBound_; + } + + /** \brief Set the bounds for the states in this space (the states will be in the set [\e lowerBound, \e + * upperBound] */ + void setBounds(int lowerBound, int upperBound) + { + lowerBound_ = lowerBound; + upperBound_ = upperBound; + } + + void setup() override; + + protected: + /** \brief The lowest integer state */ + int lowerBound_; + + /** \brief The highest integer state */ + int upperBound_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/Dubins3DMotionValidator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/Dubins3DMotionValidator.h new file mode 100644 index 00000000..0c5da567 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/Dubins3DMotionValidator.h @@ -0,0 +1,179 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2024, Metron, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Metron, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_DUBINS3D_MOTION_VALIDATOR_ +#define OMPL_BASE_SPACES_DUBINS3D_MOTION_VALIDATOR_ + +#include "ompl/base/SpaceInformation.h" +#include + +namespace ompl::base +{ + + /** + * \brief A 3D Dubins plane motion validator that only uses the state validity checker. + * Motions are checked for validity at a specified resolution. + * + * This motion validator is almost identical to the DiscreteMotionValidator except that it remembers the optimal + * PathType between different calls to interpolate. It is intended to be used with the OwenStateSpace, + * VanaStateSpace, and VanaOwenStateSpace. The SpaceInformation::setMotionValidator method uses this as the default + * for those state spaces. + */ + template + class Dubins3DMotionValidator : public MotionValidator + { + public: + Dubins3DMotionValidator(SpaceInformation *si) : MotionValidator(si) + { + defaultSettings(); + } + Dubins3DMotionValidator(const SpaceInformationPtr &si) : MotionValidator(si) + { + defaultSettings(); + } + ~Dubins3DMotionValidator() override = default; + bool checkMotion(const State *s1, const State *s2) const override + { + /* assume motion starts in a valid configuration so s1 is valid */ + if (!si_->isValid(s2)) + return false; + auto path = stateSpace_->getPath(s1, s2); + if (!path) + return false; + + bool result = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + /* initialize the queue of test positions */ + std::queue> pos; + if (nd >= 2) + { + pos.emplace(1, nd - 1); + + /* temporary storage for the checked state */ + State *test = si_->allocState(); + + /* repeatedly subdivide the path segment in the middle (and check the middle) */ + while (!pos.empty()) + { + std::pair x = pos.front(); + + int mid = (x.first + x.second) / 2; + stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, *path, test); + + if (!si_->isValid(test)) + { + result = false; + break; + } + + pos.pop(); + + if (x.first < mid) + pos.emplace(x.first, mid - 1); + if (x.second > mid) + pos.emplace(mid + 1, x.second); + } + + si_->freeState(test); + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const override + { + auto path = stateSpace_->getPath(s1, s2); + if (!path) + return false; + + /* assume motion starts in a valid configuration so s1 is valid */ + bool result = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + if (nd > 1) + { + /* temporary storage for the checked state */ + State *test = si_->allocState(); + + for (int j = 1; j < nd; ++j) + { + stateSpace_->interpolate(s1, s2, (double)j / (double)nd, *path, test); + if (!si_->isValid(test)) + { + lastValid.second = (double)(j - 1) / (double)nd; + if (lastValid.first != nullptr) + stateSpace_->interpolate(s1, s2, lastValid.second, *path, lastValid.first); + result = false; + break; + } + } + si_->freeState(test); + } + + if (result) + if (!si_->isValid(s2)) + { + lastValid.second = (double)(nd - 1) / (double)nd; + if (lastValid.first != nullptr) + stateSpace_->interpolate(s1, s2, lastValid.second, *path, lastValid.first); + result = false; + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + + private: + Dubins3DStateSpace *stateSpace_; + void defaultSettings() + { + stateSpace_ = dynamic_cast(si_->getStateSpace().get()); + if (stateSpace_ == nullptr) + throw Exception("No state space for motion validator"); + } + }; +} // namespace ompl::base + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsMotionValidator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsMotionValidator.h new file mode 100644 index 00000000..1acabafe --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsMotionValidator.h @@ -0,0 +1,180 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2025, Autonomous Systems Laboratory, ETH Zurich + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the ETH Zurich nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Jaeyoung Lim */ + +#ifndef OMPL_BASE_SPACES_DUBINS_MOTION_VALIDATOR_ +#define OMPL_BASE_SPACES_DUBINS_MOTION_VALIDATOR_ + +#include "ompl/base/SpaceInformation.h" +#include + +namespace ompl +{ + namespace base + { + /** \brief A Dubins motion validator that only uses the state validity checker. + Motions are checked for validity at a specified resolution. + + This motion validator is almost identical to the DiscreteMotionValidator + except that it remembers the optimal DubinsPath between different calls to + interpolate. */ + template + class DubinsMotionValidator : public MotionValidator + { + public: + DubinsMotionValidator(SpaceInformation *si) : MotionValidator(si) + { + defaultSettings(); + } + DubinsMotionValidator(const SpaceInformationPtr &si) : MotionValidator(si) + { + defaultSettings(); + } + ~DubinsMotionValidator() override = default; + bool checkMotion(const State *s1, const State *s2) const override + { + /* assume motion starts in a valid configuration so s1 is valid */ + if (!si_->isValid(s2)) + return false; + auto path = stateSpace_->getPath(s1, s2); + // if (!path) + // return false; + + bool result = true, firstTime = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + /* initialize the queue of test positions */ + std::queue> pos; + if (nd >= 2) + { + pos.emplace(1, nd - 1); + + /* temporary storage for the checked state */ + State *test = si_->allocState(); + + /* repeatedly subdivide the path segment in the middle (and check the middle) */ + while (!pos.empty()) + { + std::pair x = pos.front(); + + int mid = (x.first + x.second) / 2; + stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, firstTime, path, test); + + if (!si_->isValid(test)) + { + result = false; + break; + } + + pos.pop(); + + if (x.first < mid) + pos.emplace(x.first, mid - 1); + if (x.second > mid) + pos.emplace(mid + 1, x.second); + } + + si_->freeState(test); + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + + bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const override + { + /* assume motion starts in a valid configuration so s1 is valid */ + + auto path = stateSpace_->getPath(s1, s2); + // if (!path) + // return false; + + bool result = true, firstTime = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + if (nd > 1) + { + /* temporary storage for the checked state */ + State *test = si_->allocState(); + + for (int j = 1; j < nd; ++j) + { + stateSpace_->interpolate(s1, s2, (double)j / (double)nd, firstTime, path, test); + if (!si_->isValid(test)) + { + lastValid.second = (double)(j - 1) / (double)nd; + if (lastValid.first != nullptr) + stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); + result = false; + break; + } + } + si_->freeState(test); + } + + if (result) + if (!si_->isValid(s2)) + { + lastValid.second = (double)(nd - 1) / (double)nd; + if (lastValid.first != nullptr) + stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); + result = false; + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + + private: + Dubins2DStateSpace *stateSpace_; + void defaultSettings() + { + stateSpace_ = dynamic_cast(si_->getStateSpace().get()); + if (stateSpace_ == nullptr) + throw Exception("No state space for motion validator"); + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsStateSpace.h new file mode 100644 index 00000000..e319957e --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsStateSpace.h @@ -0,0 +1,170 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_DUBINS_STATE_SPACE_ +#define OMPL_BASE_SPACES_DUBINS_STATE_SPACE_ + +#include +#include "ompl/base/spaces/SE2StateSpace.h" +#include "ompl/base/MotionValidator.h" +#include + +namespace ompl +{ + namespace base + { + /** \brief An SE(2) state space where distance is measured by the + length of Dubins curves. + + Note that this Dubins distance is \b not a proper distance metric, + so nearest neighbor methods that rely on distance() being a metric + (such as ompl::NearestNeighborsGNAT) will not always return the + true nearest neighbors or get stuck in an infinite loop. + + The notation and solutions in the code are taken from:
+ A.M. Shkel and V. Lumelsky, “Classification of the Dubins set,” + Robotics and Autonomous Systems, 34(4):179-202, 2001. + DOI: 10.1016/S0921-8890(00)00127-5 + */ + class DubinsStateSpace : public SE2StateSpace + { + public: + /** \brief The Dubins path segment type */ + enum DubinsPathSegmentType + { + DUBINS_LEFT = 0, + DUBINS_STRAIGHT = 1, + DUBINS_RIGHT = 2 + }; + + /** \brief Dubins path types */ + static const std::vector> &dubinsPathType(); + + /** \brief Complete description of a Dubins path */ + class PathType + { + public: + PathType(const std::vector &type = dubinsPathType()[0], double t = 0., + double p = std::numeric_limits::max(), double q = 0.) + : type_(&type) + { + length_[0] = t; + length_[1] = p; + length_[2] = q; + assert(t >= 0.); + assert(p >= 0.); + assert(q >= 0.); + } + double length() const + { + return length_[0] + length_[1] + length_[2]; + } + + friend std::ostream &operator<<(std::ostream &os, const PathType &path); + /** Path segment types */ + const std::vector *type_; + /** Path segment lengths */ + double length_[3]; + /** Whether the path should be followed "in reverse" */ + bool reverse_{false}; + }; + + DubinsStateSpace(double turningRadius = 1.0, bool isSymmetric = false) + : rho_(turningRadius), isSymmetric_(isSymmetric) + { + setName("Dubins" + getName()); + type_ = STATE_SPACE_DUBINS; + } + + bool isMetricSpace() const override + { + return false; + } + + double distance(const State *state1, const State *state2) const override; + static double distance(const State *state1, const State *state2, double radius); + static double symmetricDistance(const State *state1, const State *state2, double radius); + + void interpolate(const State *from, const State *to, double t, State *state) const override; + virtual void interpolate(const State *from, const State *to, double t, bool &firstTime, PathType &path, + State *state) const; + virtual void interpolate(const State *from, const PathType &path, double t, State *state, + double radius) const; + + bool hasSymmetricDistance() const override + { + return isSymmetric_; + } + + bool hasSymmetricInterpolate() const override + { + return isSymmetric_; + } + + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = std::numeric_limits::epsilon(); + int flags = ~(STATESPACE_INTERPOLATION | STATESPACE_TRIANGLE_INEQUALITY | STATESPACE_DISTANCE_BOUND); + if (!isSymmetric_) + flags &= ~STATESPACE_DISTANCE_SYMMETRIC; + StateSpace::sanityChecks(zero, eps, flags); + } + + /** \brief Return a shortest Dubins path from SE(2) state state1 to SE(2) state state2 */ + PathType getPath(const State *state1, const State *state2) const; + /** \brief Return a shortest Dubins path for a vehicle with given turning radius */ + static PathType getPath(const State *state1, const State *state2, double radius); + + protected: + /** \brief Turning radius */ + double rho_; + + /** \brief Whether the distance is "symmetrized" + + If true the distance from state s1 to state s2 is the same as the + distance from s2 to s1. This is done by taking the \b minimum + length of the Dubins curves that connect s1 to s2 and s2 to s1. If + isSymmetric_ is true, then the distance no longer satisfies the + triangle inequality. */ + bool isSymmetric_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/EmptyStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/EmptyStateSpace.h new file mode 100644 index 00000000..faef86f1 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/EmptyStateSpace.h @@ -0,0 +1,82 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, + * Max Planck Institute for Intelligent Systems (MPI-IS). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the MPI-IS nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SPACES_EMPTY_STATE_SPACE_ +#define OMPL_BASE_SPACES_EMPTY_STATE_SPACE_ +#include + +namespace ompl +{ + namespace base + { + /** \brief A state space representing an empty state space. This is + * useful for multilevel representations, where some projections might + * project onto an empty state space. */ + class EmptyStateSpace : public RealVectorStateSpace + { + public: + EmptyStateSpace() : RealVectorStateSpace(0) + { + setName("EmptySpace"); + } + ~EmptyStateSpace() override = default; + + double getMeasure() const override + { + return 0; + } + + void setup() override + { + return; + } + + unsigned int getDimension() const override + { + return 0; + } + + double getMaximumExtent() const override + { + return 0; + } + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridStateSpace.h new file mode 100644 index 00000000..79c80e84 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridStateSpace.h @@ -0,0 +1,111 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2025, University of Santa Cruz Hybrid Systems Laboratory + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Santa Cruz nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Beverly Xu */ + +#ifndef OMPL_BASE_SPACES_HYBRID_STATE_SPACE_ +#define OMPL_BASE_SPACES_HYBRID_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/spaces/RealVectorStateSpace.h" +#include "HybridTimeStateSpace.h" +#include "ompl/util/Exception.h" + +namespace ompl +{ + namespace base + { + /** \brief A state space consisting of a space and a time component. */ + class HybridStateSpace : public CompoundStateSpace + { + public: + /** \brief Constructor. The maximum velocity and the weight of the time component for distance calculation + need to be specified. */ + explicit HybridStateSpace(const StateSpacePtr &spaceComponent); + + /** \brief The distance from state1 to state2. May be infinite. + * + * The distance is direction independent for compatibility to some planners (like RRTConnect). + * Make sure that the motion validator does not allow motions backwards in time or adjust the distance + * function in the Space Time State Space and the used planner. + * */ + double distance(const ompl::base::State *state1, const ompl::base::State *state2) const override; + + /** \brief The time to get from state1 to state2. */ + double timeToCoverDistance(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The distance of just the space component. */ + double distanceSpace(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The distance of just the time component. */ + double distanceTime(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The time value of the given state. */ + static double getStateTime(const ompl::base::State *state); + + /** \brief The jumps value of the given state. */ + static int getStateJumps(const ompl::base::State *state); + + /** \brief Set the jumps value of the given state. */ + static void setStateJumps(ompl::base::State *state, int jumps); + + /** \brief Set the time position value of the given state. */ + static void setStateTime(ompl::base::State *state, double position); + + /** \brief Set lower and upper time bounds for the time component. */ + void setTimeBounds(double lb, double ub); + + /** \brief The space component as a StateSpacePtr. */ + StateSpacePtr getSpaceComponent(); + + /** \brief The time component as a TimeStateSpace pointer. */ + HybridTimeStateSpace *getTimeComponent(); + + /** \brief No metric state space, as the triangle inequality is not satisfied. */ + bool isMetricSpace() const override; + + /** \brief Maximum extent is infinite, as the distance can be infinite even with bounded time. */ + double getMaximumExtent() const override; + + /** \brief Scale epsilon appropriately after time or space bounds were set. */ + void updateEpsilon(); + + protected: + /** \brief The epsilon for time distance calculation. */ + double eps_ = std::numeric_limits::epsilon(); + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridTimeStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridTimeStateSpace.h new file mode 100644 index 00000000..8e1a21c4 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridTimeStateSpace.h @@ -0,0 +1,207 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2025, University of Santa Cruz Hybrid Systems Laboratory + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Santa Cruz nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Beverly Xu */ + +#ifndef OMPL_BASE_SPACES_HYBRID_TIME_STATE_SPACE_ +#define OMPL_BASE_SPACES_HYBRID_TIME_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for time */ + class HybridTimeStateSampler : public StateSampler + { + public: + /** \brief Constructor */ + HybridTimeStateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A state space representing time. The time can be + unbounded, in which case enforceBounds() is a no-op, + satisfiesBounds() always returns true, sampling uniform + time states always produces time 0 and getMaximumExtent() + returns 1. If time is bounded (setBounds() has been + previously called), the state space behaves as + expected. After construction, the state space is + unbounded. isBounded() can be used to check if the state space + is bounded or not. */ + class HybridTimeStateSpace : public StateSpace + { + public: + /** \brief The definition of a time state */ + class StateType : public State + { + public: + /** \brief The position in time */ + double position; + + /** \brief The number of jumps */ + unsigned int jumps; + }; + + HybridTimeStateSpace() + { + setName("Hybrid Time" + getName()); + type_ = STATE_SPACE_TIME; // TODO: add STATE_SPACE_HYBRID_TIME to ompl::base::StateSpaceType + } + + ~HybridTimeStateSpace() override = default; + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + /** \brief Set the minimum and maximum time bounds. This + will make the state space switch into bounded time + mode. If this function is not called, sampling time + will always produce position = 0, enforceBounds() is a no-op, + satisfiesBounds() always returns true and + getMaximumExtent() returns 1. */ + void setTimeBounds(double minTime, double maxTime); + + /** \brief Set the minimum and maximum jump bounds. This + will make the state space switch into bounded time + mode. If this function is not called, sampling jump + will always produce jumps = 0, enforceBounds() is a no-op, + satisfiesBounds() always returns true and + getMaximumExtent() returns 1. */ + void setJumpBounds(unsigned int minJumps, unsigned int maxJumps); + + /** \brief Get the minimum allowed value of \e position in a state. The function returns 0 if time is not + * bounded. */ + double getMinTimeBound() const + { + return minTime_; + } + + /** \brief Get the maximum allowed value of \e position in a state. The function returns 0 if time is not + * bounded. */ + double getMaxTimeBound() const + { + return maxTime_; + } + + /** \brief Get the minimum allowed value of \e jumps in a state. The function returns 0 if jumps is not + * bounded. */ + double getMinJumpsBound() const + { + return minJumps_; + } + + /** \brief Get the maximum allowed value of \e jumps in a state. The function returns 0 if jumps is not + * bounded. */ + double getMaxJumpBound() const + { + return maxJumps_; + } + + /** \brief Check if the time is bounded or not */ + bool isTimeBounded() const + { + return timeBounded_; + } + + /** \brief Check if the time is bounded or not */ + bool areJumpsBounded() const + { + return jumpsBounded_; + } + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + // void registerProjections() override; + + protected: + /** \brief Flag indicating whether the state space is considering bounds or not */ + bool timeBounded_{false}; + + /** \brief The minimum point in time considered by the state space (if bounds are used) */ + double minTime_{0.0}; + + /** \brief The maximum point in time considered by the state space (if bounds are used) */ + double maxTime_{0.0}; + + /** \brief Flag indicating whether the state space is considering bounds or not */ + bool jumpsBounded_{false}; + + /** \brief The minimum point in time considered by the state space (if bounds are used) */ + unsigned int minJumps_{0}; + + /** \brief The maximum point in time considered by the state space (if bounds are used) */ + unsigned int maxJumps_{0}; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/OwenStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/OwenStateSpace.h new file mode 100644 index 00000000..05729806 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/OwenStateSpace.h @@ -0,0 +1,226 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2024, Metron, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Metron, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_OWEN_STATE_SPACE_ +#define OMPL_BASE_SPACES_OWEN_STATE_SPACE_ + +#include "ompl/base/spaces/DubinsStateSpace.h" +#include + +namespace ompl::base +{ + /** \brief An R^3 x SO(2) state space where distance is measured by the + length of a type Dubins airplane curves. + + Note that distance in this space is \b not a proper distance metric, + so nearest neighbor methods that rely on distance() being a metric + (such as ompl::NearestNeighborsGNAT) will not always return the + true nearest neighbors or get stuck in an infinite loop. + + See the following reference for details: + + [1] M. Owen, R. W. Beard, and T. W. McLain, “Implementing Dubins + airplane paths on fixed-wing UAVs,” in Handbook of Unmanned Aerial + Vehicles, Springer, 2014, pp. 1677–1701. + doi: 10.1007/978-90-481-9707-1 120 + */ + class OwenStateSpace : public CompoundStateSpace + { + public: + enum PathCategory : char + { + LOW_ALTITUDE = 'L', + MEDIUM_ALTITUDE = 'M', + HIGH_ALTITUDE = 'H', + UNKNOWN = '?' + }; + + class PathType + { + public: + PathType(DubinsStateSpace::PathType const &path, double turnRadius, double deltaZ, + unsigned int numTurns = 0) + : path_(path), turnRadius_(turnRadius), deltaZ_(deltaZ), numTurns_(numTurns) + { + } + PathType(DubinsStateSpace::PathType const &path, double turnRadius, double deltaZ, double phi) + : path_(path), turnRadius_(turnRadius), deltaZ_(deltaZ), phi_(phi) + { + } + double length() const; + + PathCategory category() const; + + friend std::ostream &operator<<(std::ostream &os, const PathType &path); + + DubinsStateSpace::PathType path_; + double turnRadius_{1.}; + double deltaZ_; + double phi_{0.}; + unsigned int numTurns_{0}; + }; + + /** A state in R^3 x SO(2): (x, y, z, yaw) */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + double operator[](unsigned index) const + { + return as(0)->values[index]; + } + double &operator[](unsigned index) + { + return as(0)->values[index]; + } + double yaw() const + { + return as(1)->value; + } + double &yaw() + { + return as(1)->value; + } + }; + + OwenStateSpace(double turningRadius = 1.0, double maxPitch = boost::math::double_constants::sixth_pi); + ~OwenStateSpace() override = default; + + bool isMetricSpace() const override + { + return false; + } + bool hasSymmetricDistance() const override + { + return false; + } + + bool hasSymmetricInterpolate() const override + { + return false; + } + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = std::numeric_limits::epsilon(); + int flags = ~(STATESPACE_INTERPOLATION | STATESPACE_TRIANGLE_INEQUALITY | STATESPACE_DISTANCE_BOUND | + STATESPACE_DISTANCE_SYMMETRIC); + StateSpace::sanityChecks(zero, eps, flags); + } + + /** \copydoc RealVectorStateSpace::setBounds() */ + void setBounds(const RealVectorBounds &bounds) + { + as(0)->setBounds(bounds); + } + + /** \copydoc RealVectorStateSpace::getBounds() */ + const RealVectorBounds &getBounds() const + { + return as(0)->getBounds(); + } + + /** Set tolerance for convergence on optimal turning radius */ + void setTolerance(double tolerance) + { + tolerance_ = tolerance; + } + /** Get tolerance for convergence on optimal turning radius */ + double getTolerance() + { + return tolerance_; + } + + State *allocState() const override; + void registerProjections() override; + + double distance(const State *state1, const State *state2) const override; + + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + /** + * \brief Compute the state that lies at time @e t in [0,1] on the segment that connects @e from state to @e to + * state. + * + * \param from start state + * \param to end state + * \param t fraction of distance along segment between @e from and @e to. Has to be between + * 0 and 1 (boundaries included). + * \param path the segment connecting @from and @to. + * \param state the state that lies on the segment at fraction @e t of the distance between + * @e from and @e to. + */ + virtual void interpolate(const State *from, const State *to, double t, PathType &path, State *state) const; + + /** + * \brief Compute a 3D Dubins path using the model and algorithm proposed by Owen et al. + * + * \param state1 start state + * \param state2 end state + * \return a 3D Dubins path if one was found, std::nullopt_t otherwise + */ + std::optional getPath(const State *state1, const State *state2) const; + + double getMinTurnRadius() const + { + return rho_; + }; + + double getMaxPitch() const + { + return atan(tanMaxPitch_); + }; + + protected: + /** + * \brief Compute the SE(2) state after making a turn + */ + void turn(const State *from, double turnRadius, double angle, State *state) const; + + /** Turning radius */ + double rho_; + /** Tan(pitch), where pitch is the maximum pitch in radians */ + double tanMaxPitch_; + /** Tolerance used to determine convergence when searching for optimal turning radius */ + double tolerance_{1e-8}; + /** Auxiliary space to compute paths in SE(2) slices of state space */ + DubinsStateSpace dubinsSpace_; + }; +} // namespace ompl::base + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorBounds.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorBounds.h new file mode 100644 index 00000000..e14c3101 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorBounds.h @@ -0,0 +1,91 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_REAL_VECTOR_BOUNDS_ +#define OMPL_BASE_SPACES_REAL_VECTOR_BOUNDS_ + +#include + +namespace ompl +{ + namespace base + { + /** \brief The lower and upper bounds for an Rn space */ + class RealVectorBounds + { + public: + /** \brief Constructor; \e dim represents the dimension of the space these bounds are for. */ + RealVectorBounds(unsigned int dim) + { + resize(dim); + } + + /** \brief Set the lower bound in each dimension to a specific value */ + void setLow(double value); + + /** \brief Set the upper bound in each dimension to a specific value */ + void setHigh(double value); + + /** \brief Set the lower bound of a dimension to a specific value */ + void setLow(unsigned int index, double value); + + /** \brief Set the upper bound of a dimension to a specific value */ + void setHigh(unsigned int index, double value); + + /** \brief Change the number of dimensions for the bounds */ + void resize(std::size_t size); + + /** \brief Compute the volume of the space enclosed by the bounds */ + double getVolume() const; + + /** \brief Get the difference between the high and low bounds for each dimension: result[i] = high[i] - + * low[i] */ + std::vector getDifference() const; + + /** \brief Check if the bounds are valid (same length for + low and high, high[i] > low[i]). Throw an exception if + this is not the case. */ + void check() const; + + /** \brief Lower bound */ + std::vector low; + + /** \brief Upper bound */ + std::vector high; + }; + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateProjections.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateProjections.h new file mode 100644 index 00000000..8a5bc90d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateProjections.h @@ -0,0 +1,202 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_REAL_VECTOR_STATE_PROJECTIONS_ +#define OMPL_BASE_SPACES_REAL_VECTOR_STATE_PROJECTIONS_ + +#include "ompl/base/ProjectionEvaluator.h" +#include "ompl/base/spaces/RealVectorStateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief Definition for a class computing linear projections + (multiplication of a k-by-n matrix to the the + Rn vector state to produce an Rk + projection. The multiplication matrix needs to be supplied + as input. */ + class RealVectorLinearProjectionEvaluator : public ProjectionEvaluator + { + public: + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + \e projection and the cell sizes are \e cellSizes. */ + RealVectorLinearProjectionEvaluator(const StateSpace *space, const std::vector &cellSizes, + const ProjectionMatrix::Matrix &projection); + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + \e projection and the cell sizes are \e cellSizes. */ + RealVectorLinearProjectionEvaluator(const StateSpacePtr &space, const std::vector &cellSizes, + const ProjectionMatrix::Matrix &projection); + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + \e projection and the cell sizes are automatically inferred through sampling. */ + RealVectorLinearProjectionEvaluator(const StateSpace *space, const ProjectionMatrix::Matrix &projection); + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + \e projection and the cell sizes are automatically inferred through sampling. */ + RealVectorLinearProjectionEvaluator(const StateSpacePtr &space, const ProjectionMatrix::Matrix &projection); + + unsigned int getDimension() const override; + + void project(const State *state, Eigen::Ref projection) const override; + + protected: + /** \brief The projection matrix */ + ProjectionMatrix projection_; + }; + + /** \brief Definition for a class computing a random linear projections */ + class RealVectorRandomLinearProjectionEvaluator : public RealVectorLinearProjectionEvaluator + { + public: + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + sampled at random and the cell sizes are automatically inferred through sampling. */ + RealVectorRandomLinearProjectionEvaluator(const StateSpace *space, const std::vector &cellSizes) + : RealVectorLinearProjectionEvaluator( + space, cellSizes, ProjectionMatrix::ComputeRandom(space->getDimension(), cellSizes.size())) + { + } + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + sampled at random and the cell sizes are automatically inferred through sampling. */ + RealVectorRandomLinearProjectionEvaluator(const StateSpacePtr &space, const std::vector &cellSizes) + : RealVectorLinearProjectionEvaluator( + space, cellSizes, ProjectionMatrix::ComputeRandom(space->getDimension(), cellSizes.size())) + { + } + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + sampled at random to produce a space of dimension \e dim and the cell sizes are automatically inferred + through sampling. */ + RealVectorRandomLinearProjectionEvaluator(const StateSpace *space, unsigned int dim) + : RealVectorLinearProjectionEvaluator( + space, + ProjectionMatrix::ComputeRandom(space->getDimension(), dim, + space->as()->getBounds().getDifference())) + { + } + + /** \brief Initialize a linear projection evaluator for state space \e space. The used projection matrix is + sampled at random to produce a space of dimension \e dim and the cell sizes are automatically inferred + through sampling. */ + RealVectorRandomLinearProjectionEvaluator(const StateSpacePtr &space, unsigned int dim) + : RealVectorLinearProjectionEvaluator( + space, + ProjectionMatrix::ComputeRandom(space->getDimension(), dim, + space->as()->getBounds().getDifference())) + { + } + }; + + /** \brief Definition for a class computing orthogonal projections */ + class RealVectorOrthogonalProjectionEvaluator : public ProjectionEvaluator + { + public: + /** \brief Initialize an orthogonal projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are in \e cellSizes */ + RealVectorOrthogonalProjectionEvaluator(const StateSpace *space, const std::vector &cellSizes, + std::vector components); + + /** \brief Initialize an orthogonal projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are in \e cellSizes */ + RealVectorOrthogonalProjectionEvaluator(const StateSpacePtr &space, const std::vector &cellSizes, + std::vector components); + + /** \brief Initialize an orthogonal projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are a tenth of the corresponding bounds from the + state space. */ + RealVectorOrthogonalProjectionEvaluator(const StateSpace *space, std::vector components); + + /** \brief Initialize an orthogonal projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are a tenth of the corresponding bounds from the + state space. */ + RealVectorOrthogonalProjectionEvaluator(const StateSpacePtr &space, std::vector components); + + unsigned int getDimension() const override; + + void defaultCellSizes() override; + + void project(const State *state, Eigen::Ref projection) const override; + + protected: + /** \brief Fill bounds_ with bounds from the state space */ + void copyBounds(); + + /** \brief The set of components selected by the projection */ + std::vector components_; + }; + + /** \brief Define the identity projection */ + class RealVectorIdentityProjectionEvaluator : public ProjectionEvaluator + { + public: + /** \brief Initialize the identity projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are in \e cellSizes */ + RealVectorIdentityProjectionEvaluator(const StateSpace *space, const std::vector &cellSizes); + + /** \brief Initialize the identity projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are in \e cellSizes */ + RealVectorIdentityProjectionEvaluator(const StateSpacePtr &space, const std::vector &cellSizes); + + /** \brief Initialize the identity projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are a tenth of the bounds from the state space. + */ + RealVectorIdentityProjectionEvaluator(const StateSpace *space); + + /** \brief Initialize the identity projection evaluator for state space \e space. The indices of the + kept components are in \e components and the cell sizes are a tenth of the bounds from the state space. + */ + RealVectorIdentityProjectionEvaluator(const StateSpacePtr &space); + + unsigned int getDimension() const override; + + void defaultCellSizes() override; + + void setup() override; + + void project(const State *state, Eigen::Ref projection) const override; + + private: + /** \brief Fill bounds_ with bounds from the state space */ + void copyBounds(); + + /** \brief The amount of data to copy from projection to state */ + std::size_t copySize_; + }; + } // namespace base +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateSpace.h new file mode 100644 index 00000000..a8ad0f68 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateSpace.h @@ -0,0 +1,206 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_REAL_VECTOR_STATE_SPACE_ +#define OMPL_BASE_SPACES_REAL_VECTOR_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/spaces/RealVectorBounds.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief State sampler for the Rn state space */ + class RealVectorStateSampler : public StateSampler + { + public: + /** \brief Constructor */ + RealVectorStateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + /** \brief Sample a state such that each component state[i] is + uniformly sampled from [near[i]-distance, near[i]+distance]. + If this interval exceeds the state space bounds, the + interval is truncated. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + /** \brief Sample a state such that each component state[i] has + a Gaussian distribution with mean mean[i] and standard + deviation stdDev. If the sampled value exceeds the state + space boundary, it is thresholded to the nearest boundary. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A state space representing Rn. The distance function is the L2 norm. */ + class RealVectorStateSpace : public StateSpace + { + public: + /** \brief The definition of a state in Rn */ + class StateType : public State + { + public: + StateType() = default; + + /** \brief Access element i of values. This does not + check whether the index is within bounds */ + double operator[](unsigned int i) const + { + return values[i]; + } + + /** \brief Access element i of values. This does not + check whether the index is within bounds */ + double &operator[](unsigned int i) + { + return values[i]; + } + + /** \brief The value of the actual vector in Rn */ + double *values; + }; + + /** \brief Constructor. The dimension of of the space needs to be specified. A space representing + Rdim will be instantiated */ + RealVectorStateSpace(unsigned int dim = 0) + : dimension_(dim), bounds_(dim), stateBytes_(dim * sizeof(double)) + { + type_ = STATE_SPACE_REAL_VECTOR; + setName("RealVector" + getName()); + dimensionNames_.resize(dim, ""); + } + + ~RealVectorStateSpace() override = default; + + /** \brief Increase the dimensionality of the state space by 1. Optionally, bounds can be specified for this + * added dimension. setup() will need to be called after adding dimensions. */ + void addDimension(double minBound = 0.0, double maxBound = 0.0); + + /** \brief Increase the dimensionality of the state space by 1 and specify the name of this dimension. + * Optionally, bounds can be specified for this added dimension. setup() will need to be called after adding + * dimensions. This function is a wrapper for the previous definition of addDimension(). */ + void addDimension(const std::string &name, double minBound = 0.0, double maxBound = 0.0); + + /** \brief Set the bounds of this state space. This defines + the range of the space in which sampling is performed. */ + void setBounds(const RealVectorBounds &bounds); + + /** \brief Set the bounds of this state space. The bounds for + each dimension will be the same: [\e low, \e high]. */ + void setBounds(double low, double high); + + /** \brief Get the bounds for this state space */ + const RealVectorBounds &getBounds() const + { + return bounds_; + } + + unsigned int getDimension() const override; + + /** \brief Each dimension can optionally have a name associated to it. If it does, this function returns + that name. + Return empty string otherwise */ + const std::string &getDimensionName(unsigned int index) const; + + /** \brief Get the index of a specific dimension, by name. Return -1 if name is not found */ + int getDimensionIndex(const std::string &name) const; + + /** \brief Set the name of a dimension */ + void setDimensionName(unsigned int index, const std::string &name); + + double getMaximumExtent() const override; + + double getMeasure() const override; + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void registerProjections() override; + + void setup() override; + + protected: + /** \brief The dimension of the space */ + unsigned int dimension_; + + /** \brief The bounds of the space (used for sampling) */ + RealVectorBounds bounds_; + + /** \brief Optional names for individual dimensions */ + std::vector dimensionNames_; + + /** \brief Map from names to index values for dimensions */ + std::map dimensionIndex_; + + private: + /** \brief The size of a state, in bytes */ + std::size_t stateBytes_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/ReedsSheppStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/ReedsSheppStateSpace.h new file mode 100644 index 00000000..8fa25f89 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/ReedsSheppStateSpace.h @@ -0,0 +1,133 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_REEDS_SHEPP_STATE_SPACE_ +#define OMPL_BASE_SPACES_REEDS_SHEPP_STATE_SPACE_ + +#include "ompl/base/spaces/SE2StateSpace.h" +#include "ompl/base/MotionValidator.h" +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief An SE(2) state space where distance is measured by the + length of Reeds-Shepp curves. + + The notation and solutions are taken from: + J.A. Reeds and L.A. Shepp, “Optimal paths for a car that goes both + forwards and backwards,” Pacific Journal of Mathematics, + 145(2):367–393, 1990. + + This implementation explicitly computes all 48 Reeds-Shepp curves + and returns a shortest valid solution. This can be improved by + using the configuration space partition described in: + P. Souères and J.-P. Laumond, “Shortest paths synthesis for a + car-like robot,” IEEE Trans. on Automatic Control, 41(5):672–688, + May 1996. + */ + class ReedsSheppStateSpace : public SE2StateSpace + { + public: + /** \brief The Reeds-Shepp path segment types */ + enum ReedsSheppPathSegmentType + { + RS_NOP = 0, + RS_LEFT = 1, + RS_STRAIGHT = 2, + RS_RIGHT = 3 + }; + /** \brief Reeds-Shepp path types */ + static const ReedsSheppPathSegmentType reedsSheppPathType[18][5]; + /** \brief Complete description of a ReedsShepp path */ + class PathType + { + public: + PathType(const ReedsSheppPathSegmentType *type = reedsSheppPathType[0], + double t = std::numeric_limits::max(), double u = 0., double v = 0., double w = 0., + double x = 0.); + double length() const + { + return totalLength_; + } + + /** Path segment types */ + const ReedsSheppPathSegmentType *type_; + /** Path segment lengths */ + double length_[5]; + /** Total length */ + double totalLength_; + }; + + ReedsSheppStateSpace(double turningRadius = 1.0) : rho_(turningRadius) + { + setName("ReedsShepp" + getName()); + type_ = STATE_SPACE_REEDS_SHEPP; + } + + double distance(const State *state1, const State *state2) const override; + unsigned int validSegmentCount(const State *state1, const State *state2) const override + { + return longestValidSegmentCountFactor_ * + (unsigned int)ceil(distance(state1, state2) / longestValidSegment_); + } + + void interpolate(const State *from, const State *to, double t, State *state) const override; + virtual void interpolate(const State *from, const State *to, double t, bool &firstTime, PathType &path, + State *state) const; + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = .1; // rarely such a large error will occur + StateSpace::sanityChecks(zero, eps, ~STATESPACE_INTERPOLATION); + } + + /** \brief Return a shortest Reeds-Shepp path from SE(2) state state1 to SE(2) state state2 */ + PathType getPath(const State *state1, const State *state2) const; + + protected: + virtual void interpolate(const State *from, const PathType &path, double t, State *state) const; + + /** \brief Turning radius */ + double rho_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE2StateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE2StateSpace.h new file mode 100644 index 00000000..30eaf931 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE2StateSpace.h @@ -0,0 +1,137 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_SE2_STATE_SPACE_ +#define OMPL_BASE_SPACES_SE2_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/spaces/RealVectorStateSpace.h" +#include "ompl/base/spaces/SO2StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief A state space representing SE(2) */ + class SE2StateSpace : public CompoundStateSpace + { + public: + /** \brief A state in SE(2): (x, y, yaw) */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + /** \brief Get the X component of the state */ + double getX() const + { + return as(0)->values[0]; + } + + /** \brief Get the Y component of the state */ + double getY() const + { + return as(0)->values[1]; + } + + /** \brief Get the yaw component of the state. This is + the rotation in plane, with respect to the Z + axis. */ + double getYaw() const + { + return as(1)->value; + } + + /** \brief Set the X component of the state */ + void setX(double x) + { + as(0)->values[0] = x; + } + + /** \brief Set the Y component of the state */ + void setY(double y) + { + as(0)->values[1] = y; + } + + /** \brief Set the X and Y components of the state */ + void setXY(double x, double y) + { + setX(x); + setY(y); + } + + /** \brief Set the yaw component of the state. This is + the rotation in plane, with respect to the Z + axis. */ + void setYaw(double yaw) + { + as(1)->value = yaw; + } + }; + + SE2StateSpace() + { + setName("SE2" + getName()); + type_ = STATE_SPACE_SE2; + addSubspace(std::make_shared(2), 1.0); + addSubspace(std::make_shared(), 0.5); + lock(); + } + + ~SE2StateSpace() override = default; + + /** \copydoc RealVectorStateSpace::setBounds() */ + void setBounds(const RealVectorBounds &bounds) + { + as(0)->setBounds(bounds); + } + + /** \copydoc RealVectorStateSpace::getBounds() */ + const RealVectorBounds &getBounds() const + { + return as(0)->getBounds(); + } + + State *allocState() const override; + void freeState(State *state) const override; + + void registerProjections() override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE3StateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE3StateSpace.h new file mode 100644 index 00000000..ebe09f77 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE3StateSpace.h @@ -0,0 +1,146 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_SE3_STATE_SPACE_ +#define OMPL_BASE_SPACES_SE3_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" +#include "ompl/base/spaces/RealVectorStateSpace.h" +#include "ompl/base/spaces/SO3StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief A state space representing SE(3) */ + class SE3StateSpace : public CompoundStateSpace + { + public: + /** \brief A state in SE(3): position = (x, y, z), quaternion = (x, y, z, w) */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + /** \brief Get the X component of the state */ + double getX() const + { + return as(0)->values[0]; + } + + /** \brief Get the Y component of the state */ + double getY() const + { + return as(0)->values[1]; + } + + /** \brief Get the Z component of the state */ + double getZ() const + { + return as(0)->values[2]; + } + + /** \brief Get the rotation component of the state */ + const SO3StateSpace::StateType &rotation() const + { + return *as(1); + } + + /** \brief Get the rotation component of the state and allow changing it as well */ + SO3StateSpace::StateType &rotation() + { + return *as(1); + } + + /** \brief Set the X component of the state */ + void setX(double x) + { + as(0)->values[0] = x; + } + + /** \brief Set the Y component of the state */ + void setY(double y) + { + as(0)->values[1] = y; + } + + /** \brief Set the Z component of the state */ + void setZ(double z) + { + as(0)->values[2] = z; + } + + /** \brief Set the X, Y and Z components of the state */ + void setXYZ(double x, double y, double z) + { + setX(x); + setY(y); + setZ(z); + } + }; + + SE3StateSpace() + { + setName("SE3" + getName()); + type_ = STATE_SPACE_SE3; + addSubspace(std::make_shared(3), 1.0); + addSubspace(std::make_shared(), 1.0); + lock(); + } + + ~SE3StateSpace() override = default; + + /** \copydoc RealVectorStateSpace::setBounds() */ + void setBounds(const RealVectorBounds &bounds) + { + as(0)->setBounds(bounds); + } + + /** \copydoc RealVectorStateSpace::getBounds() */ + const RealVectorBounds &getBounds() const + { + return as(0)->getBounds(); + } + + State *allocState() const override; + void freeState(State *state) const override; + + void registerProjections() override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO2StateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO2StateSpace.h new file mode 100644 index 00000000..096e4762 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO2StateSpace.h @@ -0,0 +1,131 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_SO2_STATE_SPACE_ +#define OMPL_BASE_SPACES_SO2_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for SO(2) */ + class SO2StateSampler : public StateSampler + { + public: + /** \brief Constructor */ + SO2StateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A state space representing SO(2). The distance + function and interpolation take into account angle + wrapping. */ + class SO2StateSpace : public StateSpace + { + public: + /** \brief The definition of a state in SO(2) */ + class StateType : public State + { + public: + /** \brief Set the state to identity -- no rotation (value = 0.0) */ + void setIdentity() + { + value = 0.0; + } + + /** \brief The value of the angle in the interval (-Pi, Pi] */ + double value; + }; + + SO2StateSpace() + { + setName("SO2" + getName()); + type_ = STATE_SPACE_SO2; + } + + ~SO2StateSpace() override = default; + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + /** \brief Normalize the value of the state to the interval [-Pi, Pi) */ + void enforceBounds(State *state) const override; + + /** \brief Check if the value of the state is in the interval [-Pi, Pi) */ + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void registerProjections() override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO3StateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO3StateSpace.h new file mode 100644 index 00000000..9bc9519c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO3StateSpace.h @@ -0,0 +1,164 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_SO3_STATE_SPACE_ +#define OMPL_BASE_SPACES_SO3_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for SO(3), using quaternion representation */ + class SO3StateSampler : public StateSampler + { + public: + /** \brief Constructor */ + SO3StateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + /** \brief To sample unit quaternions uniformly within some given + distance, we sample a 3-vector from the R^3 tangent space. + This vector is drawn uniformly random from a 3D ball centered at + the origin with radius distance. The vector is then "wrapped" + around S^3 to obtain a unit quaternion uniformly distributed + around the identity quaternion within given distance. We + pre-multiply this quaternion with the quaternion near + to center the distribution around near. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + /** \brief Sample a state such that the expected distance between + mean and state is stdDev. + + To sample a unit quaternion from a Gaussian + distribution, we sample a 3-vector from the R^3 tangent space + using a 3D Gaussian with zero mean and covariance matrix equal + to diag(stdDev^2, stdDev^2, stdDev^2). This vector is "wrapped" + around S^3 to obtain a Gaussian quaternion with zero mean. + We pre-multiply this quaternion with the quaternion mean + to get the desired mean. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A state space representing SO(3). The internal + representation is done with quaternions. The distance + between states is the angle between quaternions and + interpolation is done with slerp. */ + class SO3StateSpace : public StateSpace + { + public: + /** \brief The definition of a state in SO(3) represented as a unit quaternion + + \note The order of the elements matters in this + definition for the SO3StateUniformSampler::sample() + function. */ + class StateType : public State + { + public: + /** \brief Set the quaternion from axis-angle representation. The angle is given in radians. */ + void setAxisAngle(double ax, double ay, double az, double angle); + + /** \brief Set the state to identity -- no rotation */ + void setIdentity(); + + /** \brief X component of quaternion vector */ + double x; + + /** \brief Y component of quaternion vector */ + double y; + + /** \brief Z component of quaternion vector */ + double z; + + /** \brief scalar component of quaternion */ + double w; + }; + + SO3StateSpace() + { + setName("SO3" + getName()); + type_ = STATE_SPACE_SO3; + } + + ~SO3StateSpace() override = default; + + /** \brief Compute the norm of a state */ + double norm(const StateType *state) const; + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void registerProjections() override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SpaceTimeStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SpaceTimeStateSpace.h new file mode 100644 index 00000000..d2fed8ba --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SpaceTimeStateSpace.h @@ -0,0 +1,112 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, Technische Universität Berlin (TU Berlin) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the TU Berlin nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Francesco Grothe */ + +#ifndef OMPL_BASE_SPACES_ANIMATION_STATE_SPACE_ +#define OMPL_BASE_SPACES_ANIMATION_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief A state space consisting of a space and a time component. */ + class SpaceTimeStateSpace : public CompoundStateSpace + { + public: + /** \brief Constructor. The maximum velocity and the weight of the time component for distance calculation + need to be specified. */ + explicit SpaceTimeStateSpace(const StateSpacePtr &spaceComponent, double vMax = 1.0, + double timeWeight = 0.5); + + /** \brief The distance from state1 to state2. May be infinite. + * + * The distance is direction independent for compatibility to some planners (like RRTConnect). + * Make sure that the motion validator does not allow motions backwards in time or adjust the distance + * function in the Space Time State Space and the used planner. + * */ + double distance(const ompl::base::State *state1, const ompl::base::State *state2) const override; + + /** \brief The time to get from state1 to state2 with respect to vMax. */ + double timeToCoverDistance(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The distance of just the space component. */ + double distanceSpace(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The distance of just the time component. */ + double distanceTime(const ompl::base::State *state1, const ompl::base::State *state2) const; + + /** \brief The time value of the given state. */ + static double getStateTime(const ompl::base::State *state); + + /** \brief Set lower and upper time bounds for the time component. */ + void setTimeBounds(double lb, double ub); + + /** \brief Maximum velocity getter. */ + double getVMax() const; + + /** \brief Maximum velocity setter. */ + void setVMax(double vMax); + + /** \brief The space component as a StateSpacePtr. */ + StateSpacePtr getSpaceComponent(); + + /** \brief The time component as a TimeStateSpace pointer. */ + TimeStateSpace *getTimeComponent(); + + /** \brief No metric state space, as the triangle inequality is not satisfied. */ + bool isMetricSpace() const override; + + /** \brief Maximum extent is infinite, as the distance can be infinite even with bounded time. */ + double getMaximumExtent() const override; + + /** \brief Scale epsilon appropriately after time or space bounds were set. */ + void updateEpsilon(); + + protected: + /** \brief The maximum velocity of the space. */ + double vMax_; + + /** \brief The epsilon for time distance calculation. */ + double eps_ = std::numeric_limits::epsilon(); + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TimeStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TimeStateSpace.h new file mode 100644 index 00000000..36c5afd0 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TimeStateSpace.h @@ -0,0 +1,167 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_BASE_SPACES_TIME_STATE_SPACE_ +#define OMPL_BASE_SPACES_TIME_STATE_SPACE_ + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /** \brief State space sampler for time */ + class TimeStateSampler : public StateSampler + { + public: + /** \brief Constructor */ + TimeStateSampler(const StateSpace *space) : StateSampler(space) + { + } + + void sampleUniform(State *state) override; + void sampleUniformNear(State *state, const State *near, double distance) override; + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + /** \brief A state space representing time. The time can be + unbounded, in which case enforceBounds() is a no-op, + satisfiesBounds() always returns true, sampling uniform + time states always produces time 0 and getMaximumExtent() + returns 1. If time is bounded (setBounds() has been + previously called), the state space behaves as + expected. After construction, the state space is + unbounded. isBounded() can be used to check if the state space + is bounded or not. */ + class TimeStateSpace : public StateSpace + { + public: + /** \brief The definition of a time state */ + class StateType : public State + { + public: + /** \brief The position in time */ + double position; + }; + + TimeStateSpace() + { + setName("Time" + getName()); + type_ = STATE_SPACE_TIME; + } + + ~TimeStateSpace() override = default; + + unsigned int getDimension() const override; + + double getMaximumExtent() const override; + + double getMeasure() const override; + + /** \brief Set the minimum and maximum time bounds. This + will make the state space switch into bounded time + mode. If this function is not called, sampling time + will always produce position = 0, enforceBounds() is a no-op, + satisfiesBounds() always returns true and + getMaximumExtent() returns 1. */ + void setBounds(double minTime, double maxTime); + + /** \brief Get the minimum allowed value of \e position in a state. The function returns 0 if time is not + * bounded. */ + double getMinTimeBound() const + { + return minTime_; + } + + /** \brief Get the maximum allowed value of \e position in a state. The function returns 0 if time is not + * bounded. */ + double getMaxTimeBound() const + { + return maxTime_; + } + + /** \brief Check if the time is bounded or not */ + bool isBounded() const + { + return bounded_; + } + + void enforceBounds(State *state) const override; + + bool satisfiesBounds(const State *state) const override; + + void copyState(State *destination, const State *source) const override; + + unsigned int getSerializationLength() const override; + + void serialize(void *serialization, const State *state) const override; + + void deserialize(State *state, const void *serialization) const override; + + double distance(const State *state1, const State *state2) const override; + + bool equalStates(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + StateSamplerPtr allocDefaultStateSampler() const override; + + State *allocState() const override; + + void freeState(State *state) const override; + + double *getValueAddressAtIndex(State *state, unsigned int index) const override; + + void printState(const State *state, std::ostream &out) const override; + + void printSettings(std::ostream &out) const override; + + void registerProjections() override; + + protected: + /** \brief Flag indicating whether the state space is considering bounds or not */ + bool bounded_{false}; + + /** \brief The minimum point in time considered by the state space (if bounds are used) */ + double minTime_{0.0}; + + /** \brief The maximum point in time considered by the state space (if bounds are used) */ + double maxTime_{0.0}; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TrochoidStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TrochoidStateSpace.h new file mode 100644 index 00000000..9c949374 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TrochoidStateSpace.h @@ -0,0 +1,176 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2025, Autonomous Systems Laboratory, ETH Zurich + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the ETH Zurich nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Jaeyoung Lim */ + +#ifndef OMPL_BASE_SPACES_TROCHOID_STATE_SPACE_ +#define OMPL_BASE_SPACES_TROCHOID_STATE_SPACE_ + +#include "ompl/base/spaces/SE2StateSpace.h" +#include "ompl/base/MotionValidator.h" +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief An SE(2) state space where distance is measured by the + length of Trochoid shortest paths curves. + + The notation and solutions in the code are taken from:
+ Techy, Laszlo, and Craig A. Woolsey. "Minimum-time path planning for unmanned aerial vehicles + in steady uniform winds." Journal of guidance, control, and dynamics 32.6 (2009): 1736-1746. + + The implementation is from adapted from https://github.com/robotics-uncc/ConvectedDubins + written by Artur Wolek. + */ + class TrochoidStateSpace : public SE2StateSpace + { + public: + /** \brief The Dubins path segment type */ + enum TrochoidPathSegmentType + { + TROCHOID_LEFT = 0, + TROCHOID_STRAIGHT = 1, + TROCHOID_RIGHT = 2 + }; + + /** \brief Dubins path types */ + static const std::vector> &dubinsPathType(); + /** \brief Complete description of a Dubins path */ + class PathType + { + public: + PathType(const std::vector &type = dubinsPathType()[0], double tA = 0., + double p = std::numeric_limits::max(), double tB = 0., double t_2pi = 0.) + : type_(&type) + { + length_[0] = tA; + length_[1] = p; + length_[2] = t_2pi - tB; + assert(tA >= 0.); + assert(p >= 0.); + assert(t_2pi - tB >= 0.); + } + double length() const + { + return length_[0] + length_[1] + length_[2]; + } + + friend std::ostream &operator<<(std::ostream &os, const PathType &path); + /** Path segment types */ + const std::vector *type_; + /** Path segment lengths */ + double length_[3]; + /** Whether the path should be followed "in reverse" */ + bool reverse_{false}; + }; + + TrochoidStateSpace(double turningRadius = 1.0, double windRatio = 0.0, double windDirection = 0.0, + bool isSymmetric = false) + : rho_(turningRadius), eta_(windRatio), psi_w_(windDirection), isSymmetric_(isSymmetric) + { + setName("Trochoid" + getName()); + type_ = STATE_SPACE_TROCHOID; + } + + bool isMetricSpace() const override + { + return false; + } + + double distance(const State *state1, const State *state2) const override; + static double distance(const State *state1, const State *state2, double radius, double wind_ratio, + double wind_heading); + static double symmetricDistance(const State *state1, const State *state2, double radius, double wind_ratio, + double wind_heading); + + void interpolate(const State *from, const State *to, double t, State *state) const override; + virtual void interpolate(const State *from, const State *to, double t, bool &firstTime, PathType &path, + State *state) const; + virtual void interpolate(const State *from, const PathType &path, double t, State *state, double radius, + double wind_ratio, double wind_heading) const; + + bool hasSymmetricDistance() const override + { + return isSymmetric_; + } + + bool hasSymmetricInterpolate() const override + { + return isSymmetric_; + } + + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = std::numeric_limits::epsilon(); + int flags = ~(STATESPACE_INTERPOLATION | STATESPACE_TRIANGLE_INEQUALITY | STATESPACE_DISTANCE_BOUND); + if (!isSymmetric_) + flags &= ~STATESPACE_DISTANCE_SYMMETRIC; + StateSpace::sanityChecks(zero, eps, flags); + } + + /** \brief Return a shortest Dubins path from SE(2) state state1 to SE(2) state state2 */ + PathType getPath(const State *state1, const State *state2, bool periodic = false) const; + /** \brief Return a shortest Dubins path for a vehicle with given turning radius */ + static PathType getPath(const State *state1, const State *state2, double radius, double wind_ratio, + double wind_heading, bool periodic = false); + + protected: + /** \brief Turning radius */ + double rho_; + + /** \brief Wind ratio */ + double eta_; + + /** \brief Wind direction [0, 2pi] */ + double psi_w_; + + /** \brief Whether the distance is "symmetrized" + + If true the distance from state s1 to state s2 is the same as the + distance from s2 to s1. This is done by taking the \b minimum + length of the Dubins curves that connect s1 to s2 and s2 to s1. If + isSymmetric_ is true, then the distance no longer satisfies the + triangle inequality. */ + bool isSymmetric_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaOwenStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaOwenStateSpace.h new file mode 100644 index 00000000..404ce846 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaOwenStateSpace.h @@ -0,0 +1,254 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2024, Metron, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Metron, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_VANAOWEN_STATE_SPACE_ +#define OMPL_BASE_SPACES_VANAOWEN_STATE_SPACE_ + +#include "ompl/base/spaces/DubinsStateSpace.h" +#include + +namespace ompl::base +{ + /** \brief An R^4 x SO(2) state space where distance is measured by the + length of a type of Dubins airplane curves. + + Note that distance in this space is \b not a proper distance metric, + so nearest neighbor methods that rely on distance() being a metric + (such as ompl::NearestNeighborsGNAT) will not always return the + true nearest neighbors or get stuck in an infinite loop. + + See the following reference for details: + + [1] M. Moll, "3D Dubins Paths for Underwater Vehicles," OCEANS 2024 - Halifax, Halifax, NS, Canada, 2024. + doi: 10.1109/OCEANS55160.2024.10754581. + */ + class VanaOwenStateSpace : public CompoundStateSpace + { + public: + enum PathCategory : char + { + LOW_ALTITUDE = 'L', + MEDIUM_ALTITUDE = 'M', + HIGH_ALTITUDE = 'H', + UNKNOWN = '?' + }; + + class PathType + { + public: + PathType(); + PathType(const PathType &path); + ~PathType(); + double length() const; + PathType &operator=(const PathType &path); + + PathCategory category() const; + + friend std::ostream &operator<<(std::ostream &os, const PathType &path); + + DubinsStateSpace::PathType pathXY_; + DubinsStateSpace::PathType pathSZ_; + DubinsStateSpace::StateType *startSZ_{nullptr}; + double horizontalRadius_{1.}; + double verticalRadius_{1.}; + double deltaZ_{0.}; + double phi_{0.}; + unsigned int numTurns_{0}; + }; + + /** A state in R^4 x SO(2): (x, y, z, pitch, yaw) */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + double operator[](unsigned index) const + { + return as(0)->values[index]; + } + double &operator[](unsigned index) + { + return as(0)->values[index]; + } + double yaw() const + { + return as(1)->value; + } + double &yaw() + { + return as(1)->value; + } + double pitch() const + { + return as(0)->values[3]; + } + double &pitch() + { + return as(0)->values[3]; + } + }; + + VanaOwenStateSpace(double turningRadius = 1.0, double maxPitch = boost::math::double_constants::sixth_pi); + VanaOwenStateSpace(double turningRadius, std::pair pitchRange); + ~VanaOwenStateSpace() override = default; + + bool isMetricSpace() const override + { + return false; + } + bool hasSymmetricDistance() const override + { + return false; + } + + bool hasSymmetricInterpolate() const override + { + return false; + } + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = std::numeric_limits::epsilon(); + int flags = ~(STATESPACE_INTERPOLATION | STATESPACE_TRIANGLE_INEQUALITY | STATESPACE_DISTANCE_BOUND | + STATESPACE_DISTANCE_SYMMETRIC); + StateSpace::sanityChecks(zero, eps, flags); + } + + /** \copydoc RealVectorStateSpace::setBounds() */ + void setBounds(const RealVectorBounds &bounds) + { + RealVectorBounds b(bounds); + if (bounds.low.size() < 4) + { + b.resize(4); + b.low[3] = minPitch_; + b.high[3] = maxPitch_; + } + as(0)->setBounds(b); + } + + /** \copydoc RealVectorStateSpace::getBounds() */ + const RealVectorBounds &getBounds() const + { + return as(0)->getBounds(); + } + + /** Set tolerance for convergence on optimal turning radius */ + void setTolerance(double tolerance) + { + tolerance_ = tolerance; + } + /** Get tolerance for convergence on optimal turning radius */ + double getTolerance() + { + return tolerance_; + } + + State *allocState() const override; + void registerProjections() override; + + double distance(const State *state1, const State *state2) const override; + + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + /** + * \brief Compute the state that lies at time @e t in [0,1] on the segment that connects @e from state to @e to + * state. + * + * \param from start state + * \param to end state + * \param t fraction of distance along segment between @e from and @e to. Has to be between + * 0 and 1 (boundaries included). + * \param path the segment connecting @from and @to. + * \param state the state that lies on the segment at fraction @e t of the distance between + * @e from and @e to. + */ + virtual void interpolate(const State *from, const State *to, double t, PathType &path, State *state) const; + + /** + * \brief Compute a 3D Dubins path using the model and algorithm proposed by VanaOwen et al. + * + * \param state1 start state + * \param state2 end state + * \return a 3D Dubins path if one was found, std::nullopt_t otherwise + */ + std::optional getPath(const State *state1, const State *state2) const; + + /** + * \brief Helper function used by getPath + * + * \param state1 start state + * \param state2 end state + * \param radius turning radius for the motion in the XY plane + * \param path resulting path + * \param endSZ working memory + * \return true iff a feasible solution was found + */ + bool decoupled(const StateType *state1, const StateType *state2, double radius, PathType &path, + std::array &scratch) const; + + protected: + /** + * \brief Allocate a DubinsSpace state and initialize it + * + * \param x initial X coordinate of allocated state + * \param y initial Y coordinate of allocated state + * \param yaw initial yaw coordinate of allocated state + * \return new allocated and initialized state + */ + DubinsStateSpace::StateType *get2DPose(double x, double y, double yaw) const; + + /** + * \brief Whether a path in SZ space satisfies Dubins path type and pitch constraints + * \return true iff path is of type LRL or RLR and the pitch in state lies in-between min and max pitch + */ + bool isValid(DubinsStateSpace::PathType const &path, StateType const *state) const; + + /** Turning radius */ + double rho_; + /** Minimum pitch in radians */ + double minPitch_; + /** Maximum pitch in radians */ + double maxPitch_; + /** Tolerance used to determine convergence when searching for optimal turning radius */ + double tolerance_{1e-8}; + /** Auxiliary space to compute paths in SE(2) slices of state space */ + DubinsStateSpace dubinsSpace_; + }; +} // namespace ompl::base + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaStateSpace.h new file mode 100644 index 00000000..efcdb47e --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaStateSpace.h @@ -0,0 +1,248 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2024, Metron, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Metron, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_BASE_SPACES_VANA_STATE_SPACE_ +#define OMPL_BASE_SPACES_VANA_STATE_SPACE_ + +#include "ompl/base/spaces/DubinsStateSpace.h" +#include + +namespace ompl::base +{ + /** \brief An R^4 x SO(2) state space where distance is measured by the + length of a type Dubins airplane curves. + + Note that distance in this space is \b not a proper distance metric, + so nearest neighbor methods that rely on distance() being a metric + (such as ompl::NearestNeighborsGNAT) will not always return the + true nearest neighbors or get stuck in an infinite loop. + + See the following reference for details: + + [1] P. Váňa, A. Alves Neto, J. Faigl, and D. G. Macharet, “Minimal 3D Dubins + Path with Bounded Curvature and Pitch Angle,” in 2020 IEEE International + Conference on Robotics and Automation (ICRA), May 2020, pp. 8497–8503. + doi: 10.1109/ICRA40945.2020.9197084. + */ + class VanaStateSpace : public CompoundStateSpace + { + public: + class PathType + { + public: + PathType(); + PathType(const PathType &path); + ~PathType(); + double length() const; + PathType &operator=(const PathType &path); + + friend std::ostream &operator<<(std::ostream &os, const PathType &path); + + double horizontalRadius_{1.}; + double verticalRadius_{1.}; + + DubinsStateSpace::PathType pathXY_; + DubinsStateSpace::PathType pathSZ_; + DubinsStateSpace::StateType *startSZ_{nullptr}; + }; + + /** A state in R^4 x SO(2): (x, y, z, pitch, yaw) */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + double operator[](unsigned index) const + { + return as(0)->values[index]; + } + double &operator[](unsigned index) + { + return as(0)->values[index]; + } + double yaw() const + { + return as(1)->value; + } + double &yaw() + { + return as(1)->value; + } + double pitch() const + { + return as(0)->values[3]; + } + double &pitch() + { + return as(0)->values[3]; + } + }; + + VanaStateSpace(double turningRadius = 1.0, double maxPitch = boost::math::double_constants::sixth_pi); + VanaStateSpace(double turningRadius, std::pair pitchRange); + ~VanaStateSpace() override = default; + + bool isMetricSpace() const override + { + return false; + } + bool hasSymmetricDistance() const override + { + return false; + } + + bool hasSymmetricInterpolate() const override + { + return false; + } + + void sanityChecks() const override + { + double zero = std::numeric_limits::epsilon(); + double eps = std::numeric_limits::epsilon(); + int flags = ~(STATESPACE_INTERPOLATION | STATESPACE_TRIANGLE_INEQUALITY | STATESPACE_DISTANCE_BOUND | + STATESPACE_DISTANCE_SYMMETRIC); + StateSpace::sanityChecks(zero, eps, flags); + } + + /** \copydoc RealVectorStateSpace::setBounds() */ + void setBounds(const RealVectorBounds &bounds) + { + RealVectorBounds b(bounds); + if (bounds.low.size() < 4) + { + b.resize(4); + b.low[3] = minPitch_; + b.high[3] = maxPitch_; + } + as(0)->setBounds(b); + } + + /** \copydoc RealVectorStateSpace::getBounds() */ + const RealVectorBounds &getBounds() const + { + return as(0)->getBounds(); + } + + /** Set tolerance for convergence on optimal turning radius */ + void setTolerance(double tolerance) + { + tolerance_ = tolerance; + } + /** Get tolerance for convergence on optimal turning radius */ + double getTolerance() + { + return tolerance_; + } + + State *allocState() const override; + void registerProjections() override; + + double distance(const State *state1, const State *state2) const override; + + unsigned int validSegmentCount(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + /** + * \brief Compute the state that lies at time @e t in [0,1] on the segment that connects @e from state to @e to + * state. + * + * \param from start state + * \param to end state + * \param t fraction of distance along segment between @e from and @e to. Has to be between + * 0 and 1 (boundaries included). + * \param path the segment connecting @from and @to. + * \param state the state that lies on the segment at fraction @e t of the distance between + * @e from and @e to. + */ + virtual void interpolate(const State *from, const State *to, double t, PathType &path, State *state) const; + /** + * \brief Compute the state that lies at time @e t in [0,1] on the segment @e path starting from state @e from. + * + * \param from start state + * \param path a segment + * \param t fraction of distance along segment @path. Has to be between 0 and 1 (boundaries included). + * \param state the state that lies on the segment at fraction @e t of the distance along @e path, + * starting from state @e from. + */ + virtual void interpolate(const State *from, const PathType &path, double t, State *state) const; + + /** + * \brief Compute a 3D Dubins path using the model and algorithm proposed by Vana et al. + * + * \param state1 start state + * \param state2 end state + * \return a 3D Dubins path if one was found, std::nullopt_t otherwise + */ + std::optional getPath(const State *state1, const State *state2) const; + + /** + * \brief Helper function used by getPath + * + * \param state1 start state + * \param state2 end state + * \param radius turning radius for the motion in the XY plane + * \param path resulting path + * \param endSZ working memory + * \return true iff a feasible solution was found + */ + bool decoupled(const State *state1, const State *state2, double radius, PathType &path, + DubinsStateSpace::StateType *endSZ) const; + + protected: + /** + * \brief Allocate a DubinsSpace state and initialize it + * + * \param x initial X coordinate of allocated state + * \param y initial Y coordinate of allocated state + * \param yaw initial yaw coordinate of allocated state + * \return new allocated and initialized state + */ + DubinsStateSpace::StateType *get2DPose(double x, double y, double yaw) const; + + /** Turning radius */ + double rho_; + /** Minimum pitch in radians */ + double minPitch_; + /** Maximum pitch in radians */ + double maxPitch_; + /** Tolerance used to determine convergence when searching for optimal turning radius */ + double tolerance_{1e-8}; + /** Auxiliary space to compute paths in SE(2) slices of state space */ + DubinsStateSpace dubinsSpace_; + }; +} // namespace ompl::base + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/WrapperStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/WrapperStateSpace.h new file mode 100644 index 00000000..dedf6b70 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/WrapperStateSpace.h @@ -0,0 +1,425 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston */ + +#ifndef OMPL_BASE_SPACES_WRAPPER_STATE_SPACE_ +#define OMPL_BASE_SPACES_WRAPPER_STATE_SPACE_ + +#include + +#include "ompl/base/StateSpace.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::WrapperStateSpace */ + OMPL_CLASS_FORWARD(WrapperStateSpace); + /// @endcond + + /** \brief A state sampler that wraps around another state sampler. */ + class WrapperStateSampler : public StateSampler + { + public: + /** \brief Constructor. Requires the wrapper state space \a space + * and the underlying sampler \a sampler. */ + WrapperStateSampler(const StateSpace *space, StateSamplerPtr sampler) + : StateSampler(space), sampler_(std::move(sampler)) + { + } + + /** \brief Sample a state using underlying sampler. */ + void sampleUniform(State *state) override; + + /** \brief Sample a nearby state using underlying sampler. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + + /** \brief Sample a state within a Gaussian distribution using underlying sampler. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + protected: + /** \brief Underlying state sampler. */ + StateSamplerPtr sampler_; + }; + + /** \brief A projection evaluator that wraps around another projection + * evaluator. */ + class WrapperProjectionEvaluator : public ProjectionEvaluator + { + public: + WrapperProjectionEvaluator(const WrapperStateSpace *space); + + void setup() override; + + unsigned int getDimension() const override; + + void project(const State *state, Eigen::Ref projection) const override; + + private: + /** \brief Projection from wrapped space. */ + ProjectionEvaluatorPtr projection_; + }; + + /** \brief State space wrapper that transparently passes state space + * operations through to the underlying space. Allows augmentation of + * state spaces with additional information. */ + class WrapperStateSpace : public StateSpace + { + public: + /** \brief Wrapper state type. Contains a reference to an underlying state. */ + class StateType : public State + { + public: + /** \brief Constructor. Takes a reference \a state to the underlying state. */ + StateType(State *state) : state_(state) + { + } + + /** \brief Get a const pointer to the underlying state. */ + const State *getState() const + { + return state_; + } + + /** \brief Get a pointer to the underlying state. */ + State *getState() + { + return state_; + } + + protected: + /** \brief Underlying state. */ + State *state_; + }; + + WrapperStateSpace(const StateSpacePtr &space) : space_(space) + { + } + + bool isCompound() const override + { + return space_->isCompound(); + } + + bool isDiscrete() const override + { + return space_->isDiscrete(); + } + + bool isHybrid() const override + { + return space_->isHybrid(); + } + + bool isMetricSpace() const override + { + return space_->isMetricSpace(); + } + + bool hasSymmetricDistance() const override + { + return space_->hasSymmetricDistance(); + } + + bool hasSymmetricInterpolate() const override + { + return space_->hasSymmetricInterpolate(); + } + + const std::string &getName() const + { + return space_->getName(); + } + + void setName(const std::string &name) + { + space_->setName(name); + } + + int getType() const + { + return space_->getType(); + } + + bool includes(const StateSpacePtr &other) const + { + return space_->includes(other); + } + + bool includes(const StateSpace *other) const + { + return space_->includes(other); + } + + bool covers(const StateSpacePtr &other) const + { + return space_->covers(other); + } + + bool covers(const StateSpace *other) const + { + return space_->covers(other); + } + + ParamSet ¶ms() + { + return space_->params(); + } + + /** \brief Get the parameters for this space */ + const ParamSet ¶ms() const + { + return space_->params(); + } + + double getLongestValidSegmentFraction() const override + { + return space_->getLongestValidSegmentFraction(); + } + + void setLongestValidSegmentFraction(double segmentFraction) override + { + space_->setLongestValidSegmentFraction(segmentFraction); + } + + unsigned int validSegmentCount(const State *state1, const State *state2) const override + { + return space_->validSegmentCount(state1->as()->getState(), + state2->as()->getState()); + } + + void setValidSegmentCountFactor(unsigned int factor) override + { + space_->setValidSegmentCountFactor(factor); + } + + unsigned int getValidSegmentCountFactor() const override + { + return space_->getValidSegmentCountFactor(); + } + + double getLongestValidSegmentLength() const override + { + return space_->getLongestValidSegmentLength(); + } + + void computeSignature(std::vector &signature) const override + { + space_->computeSignature(signature); + } + + unsigned int getDimension() const override + { + return space_->getDimension(); + } + + double getMaximumExtent() const override + { + return space_->getMaximumExtent(); + } + + double getMeasure() const override + { + return space_->getMeasure(); + } + + void enforceBounds(State *state) const override + { + space_->enforceBounds(state->as()->getState()); + } + + bool satisfiesBounds(const State *state) const override + { + return space_->satisfiesBounds(state->as()->getState()); + } + + void copyState(State *destination, const State *source) const override + { + space_->copyState(destination->as()->getState(), source->as()->getState()); + } + + double distance(const State *state1, const State *state2) const override + { + return space_->distance(state1->as()->getState(), state2->as()->getState()); + } + + unsigned int getSerializationLength() const override + { + return space_->getSerializationLength(); + } + + void serialize(void *serialization, const State *state) const override + { + space_->serialize(serialization, state->as()->getState()); + } + + void deserialize(State *state, const void *serialization) const override + { + space_->deserialize(state->as()->getState(), serialization); + } + + bool equalStates(const State *state1, const State *state2) const override + { + return space_->equalStates(state1->as()->getState(), state2->as()->getState()); + } + + void interpolate(const State *from, const State *to, double t, State *state) const override + { + return space_->interpolate(from->as()->getState(), to->as()->getState(), t, + state->as()->getState()); + } + + StateSamplerPtr allocDefaultStateSampler() const override + { + return std::make_shared(this, space_->allocDefaultStateSampler()); + } + + State *allocState() const override + { + return new StateType(space_->allocState()); + } + + void freeState(State *state) const override + { + auto *wstate = state->as(); + space_->freeState(wstate->getState()); + delete wstate; + } + + double *getValueAddressAtIndex(State *state, unsigned int index) const override + { + return space_->getValueAddressAtIndex(state->as()->getState(), index); + } + + const double *getValueAddressAtIndex(const State *state, unsigned int index) const override + { + return space_->getValueAddressAtIndex(state->as()->getState(), index); + } + + const std::vector &getValueLocations() const override + { + return space_->getValueLocations(); + } + + const std::map &getValueLocationsByName() const override + { + return space_->getValueLocationsByName(); + } + + double *getValueAddressAtLocation(State *state, const ValueLocation &loc) const override + { + return space_->getValueAddressAtLocation(state->as()->getState(), loc); + } + + const double *getValueAddressAtLocation(const State *state, const ValueLocation &loc) const override + { + return space_->getValueAddressAtLocation(state->as()->getState(), loc); + } + + double *getValueAddressAtName(State *state, const std::string &name) const override + { + return space_->getValueAddressAtName(state->as()->getState(), name); + } + + const double *getValueAddressAtName(const State *state, const std::string &name) const override + { + return space_->getValueAddressAtName(state->as()->getState(), name); + } + + void copyToReals(std::vector &reals, const State *source) const override + { + space_->copyToReals(reals, source->as()->getState()); + } + + void copyFromReals(State *destination, const std::vector &reals) const override + { + space_->copyFromReals(destination->as()->getState(), reals); + } + + void registerProjections() override + { + space_->registerProjections(); + } + + void printState(const State *state, std::ostream &out = std::cout) const override + { + space_->printState(state->as()->getState(), out); + } + + void printSettings(std::ostream &out) const override + { + space_->printSettings(out); + } + + void printProjections(std::ostream &out) const override + { + space_->printProjections(out); + } + + void sanityChecks(double zero, double eps, unsigned int flags) const override + { + space_->sanityChecks(zero, eps, flags); + } + + void sanityChecks() const override + { + space_->sanityChecks(); + } + + StateSamplerPtr allocSubspaceStateSampler(const StateSpace *subspace) const override + { + return space_->allocSubspaceStateSampler(subspace); + } + + void computeLocations() override + { + space_->computeLocations(); + } + + void setup() override; + + const StateSpacePtr &getSpace() const + { + return space_; + } + + protected: + const StateSpacePtr space_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasChart.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasChart.h new file mode 100644 index 00000000..45cffda5 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasChart.h @@ -0,0 +1,269 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston, Caleb Voss */ + +#ifndef OMPL_BASE_SPACES_ATLAS_CHART_ +#define OMPL_BASE_SPACES_ATLAS_CHART_ + +#include "ompl/base/spaces/constraint/AtlasStateSpace.h" +#include "ompl/datastructures/PDF.h" + +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief Tangent space and bounding polytope approximating some patch + * of the manifold. */ + class AtlasChart + { + private: + /** \brief Halfspace equation on a chart. \note Use + * AtlasChart::generateHalfspace to create new halfspace objects. + * Since each halfspace is associated to exactly one chart, we let + * the chart be responsible for deleting it. */ + class Halfspace + { + public: + // non-copyable + Halfspace(const Halfspace &) = delete; + Halfspace &operator=(const Halfspace &) = delete; + + /** \brief Create a halfspace equitably separating charts \a + * owner and \a neighbor. This halfspace will coincide with + * chart \a owner. */ + Halfspace(const AtlasChart *owner, const AtlasChart *neighbor); + + /** \brief Return whether point \a v on the owning chart + * lies within the halfspace. */ + bool contains(const Eigen::Ref &v) const; + + /** \brief If point \a v on the owning chart is very close to + * the halfspace boundary, the "complementary" halfspace will + * extend its boundary so that it also contains \a v when \a v + * is projected onto the neighboring chart. */ + void checkNear(const Eigen::Ref &v) const; + + /** \brief Compute up to two vertices of intersection with a + * circle of radius \a r. If one vertex is found, it is stored + * to both \a v1 and \a v2; if two are found, they are stored to + * \a v1 and \a v2. If no vertex is found, returns false; + * otherwise returns true. */ + bool circleIntersect(double r, Eigen::Ref v1, Eigen::Ref v2) const; + + /** \brief Compute the vertex of intersection of two + * 1-dimensional inequalities \a l1 and \a l2. Result stored in + * \a out, which should be allocated to a size of 2. */ + static void intersect(const Halfspace &l1, const Halfspace &l2, Eigen::Ref out); + + /** \brief Inform this halfspace about the "complementary" + * halfspace which coincides with the neighboring chart. */ + void setComplement(Halfspace *complement) + { + complement_ = complement; + } + + /** \brief Get the complementary halfspace. */ + Halfspace *getComplement() const + { + return complement_; + } + + /** \brief Get the chart to which this halfspace belongs. */ + const AtlasChart *getOwner() const + { + return owner_; + } + + private: + /** \brief Chart to which this halfspace belongs. */ + const AtlasChart *owner_; + + /** \brief Halfspace complementary to this one, but on the + * neighboring chart. */ + Halfspace *complement_{nullptr}; + + /** \brief Center of the neighboring chart projected onto our + * chart. */ + Eigen::VectorXd u_; + + /** \brief Precomputed squared norm of u_ */ + double usqnorm_; + + /** \brief Precomputed right-hand side of the inequality. */ + double rhs_; + + /** \brief Generate the linear inequality. We will divide the + * space in half between \a u and 0, and 0 will lie inside. */ + void setU(const Eigen::Ref &u); + + /** \brief Compute the distance between a point \a v on our + * chart and the halfspace boundary as a scalar factor of + * \a u_. That is, \a result * \a u_ lies on the halfspace + * boundary, and \a v, \a u_, \a result * \a u_ are colinear. */ + double distanceToPoint(const Eigen::Ref &v) const; + + /** \brief Expand the halfspace to include ambient point \a x + * when it is projected onto our chart. */ + void expandToInclude(const Eigen::Ref &x); + }; + + public: + // non-copyable + AtlasChart(const AtlasChart &) = delete; + AtlasChart &operator=(const AtlasChart &) = delete; + + /** \brief Create a tangent space chart for \a atlas with center at + * ambient space point \a xorigin. + * \throws ompl::Exception when manifold seems degenerate here. */ + AtlasChart(const AtlasStateSpace *atlas, const AtlasStateSpace::StateType *state); + + /** \brief Destructor. */ + ~AtlasChart(); + + /** \brief Forget all acquired information such as the halfspace + * boundary. */ + void clear(); + + /** \brief Returns phi(0), the center of the chart in ambient + * space. */ + const AtlasStateSpace::StateType *getOrigin() const + { + return state_; + } + + /** \brief Returns the dimension of the ambient space. */ + unsigned int getAmbientDimension() const + { + return n_; + } + + /** \brief Returns the dimension of the manifold. */ + unsigned int getManifoldDimension() const + { + return k_; + } + + /** \brief Rewrite a chart point \a u in ambient space coordinates + * and store the result in \a out, which should be allocated to size + * n_. + */ + void phi(const Eigen::Ref &u, Eigen::Ref out) const; + + /** \brief Exponential mapping. Project chart point \a u onto the + * manifold and store the result in \a out, which should be + * allocated to size n_. */ + bool psi(const Eigen::Ref &u, Eigen::Ref out) const; + + /** \brief Logarithmic mapping. Project ambient point \a x onto the + * chart and store the result in \a out, which should be allocated + * to size k_. */ + void psiInverse(const Eigen::Ref &x, Eigen::Ref out) const; + + /** \brief Check if a point \a u on the chart lies within its + * polytope boundary. Can ignore up to 2 of the halfspaces if + * specified in \a ignore1 and \a ignore2. */ + bool inPolytope(const Eigen::Ref &u, const Halfspace *ignore1 = nullptr, + const Halfspace *ignore2 = nullptr) const; + + /** \brief Check if chart point \a v lies very close to any part of + * the boundary. Wherever it does, expand the neighboring chart's + * boundary to include. */ + void borderCheck(const Eigen::Ref &v) const; + + /** \brief Try to find an owner for ambient point \x from among the + * neighbors of this chart. Returns nullptr if none found.*/ + const AtlasChart *owningNeighbor(const Eigen::Ref &x) const; + + /** \brief For manifolds of dimension 2, return in order in \a + * vertices the polygon boundary of this chart, including an + * approximation of the circular boundary where the polygon exceeds + * radius \a rho_. Returns true if a circular portion is + * included. */ + bool toPolygon(std::vector &vertices) const; + + /** \brief Returns the number of charts this chart shares a + * halfspace boundary with. */ + std::size_t getNeighborCount() const + { + return polytope_.size(); + } + + /** \brief Use sampling to make a quick estimate as to whether this + * chart's polytope boundary is completely defined by its + * halfspaces. */ + bool estimateIsFrontier() const; + + /** \brief Create two complementary halfspaces dividing the space + * between charts \a c1 and \a c2, and add them to the charts' + * polytopes boundaries. + * \note Charts must be different charts from the same atlas. */ + static void generateHalfspace(AtlasChart *c1, AtlasChart *c2); + + protected: + /** \brief The constraint function that defines the manifold. */ + const Constraint *constraint_; + + /** \brief Set of halfspaces defining the polytope boundary. */ + std::vector polytope_; + + /** \brief Introduce a new \a halfspace to the chart's bounding + * polytope. This chart assumes responsibility for deleting \a + * halfspace. */ + void addBoundary(Halfspace *halfspace); + + private: + /** \brief Dimension of the ambient space. */ + const unsigned int n_; + + /** \brief Dimension of the chart, which is the dimension of the + * manifold. */ + const unsigned int k_; + + /** \brief Origin of the chart in ambient space coordinates. */ + const AtlasStateSpace::StateType *state_; + + /** \brief Basis for the chart space. */ + const Eigen::MatrixXd bigPhi_; + + /** \brief Maximum valid radius of this chart. */ + const double radius_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasStateSpace.h new file mode 100644 index 00000000..685feb7a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasStateSpace.h @@ -0,0 +1,437 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston, Caleb Voss */ + +#ifndef OMPL_BASE_SPACES_ATLAS_STATE_SPACE_ +#define OMPL_BASE_SPACES_ATLAS_STATE_SPACE_ + +#include "ompl/base/StateSampler.h" +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/Constraint.h" +#include "ompl/datastructures/NearestNeighborsGNAT.h" +#include "ompl/datastructures/PDF.h" + +#include "ompl/base/spaces/constraint/ConstrainedStateSpace.h" + +#include + +namespace ompl +{ + namespace magic + { + static const unsigned int ATLAS_STATE_SPACE_SAMPLES = 50; + static const double ATLAS_STATE_SPACE_EPSILON = 0.05; + static const double ATLAS_STATE_SPACE_RHO_MULTIPLIER = 5; + static const double ATLAS_STATE_SPACE_ALPHA = boost::math::constants::pi() / 8.0; + static const double ATLAS_STATE_SPACE_EXPLORATION = 0.75; + static const unsigned int ATLAS_STATE_SPACE_MAX_CHARTS_PER_EXTENSION = 200; + static const double ATLAS_STATE_SPACE_BACKOFF = 0.75; + } // namespace magic + + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::AtlasChart */ + OMPL_CLASS_FORWARD(AtlasChart); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::AtlasStateSpace */ + OMPL_CLASS_FORWARD(AtlasStateSpace); + /// @endcond + + /** \brief StateSampler for use on an atlas. */ + class AtlasStateSampler : public StateSampler + { + public: + AtlasStateSampler(const AtlasStateSpace *space); + + /** \brief Sample a state uniformly from the charted regions of the + * manifold. Return sample in \a state. */ + void sampleUniform(State *state) override; + + /** \brief Sample a state uniformly from the ball with center \a + * near and radius \a distance. Return sample in \a state. \note + * rho_s_ is a good choice for \a distance. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + + /** \brief Sample a state uniformly from a normal distribution with + given \a mean and \a stdDev. Return sample in \a state. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + private: + /** \brief Atlas on which to sample. */ + const AtlasStateSpace *atlas_; + + /** \brief Random number generator. */ + mutable RNG rng_; + }; + + /** + @anchor gAtlas + @par Short Description + AtlasStateSpace implements an atlas-based methodology for constrained sampling-based planning, + where the underlying constraint manifold is locally parameterized by \e charts (AtlasChart). The underlying + constraint manifold can then be sampled and explored using the collection of these charts (an \e atlas). + + @par External Documentation + This state space is inspired by the work on AtlasRRT. One reference of which is the following: + + L. Jaillet and J. M. Porta, "Path Planning Under Kinematic Constraints by Rapidly Exploring Manifolds," in + IEEE Transactions on Robotics, vol. 29, no. 1, pp. 105-117, Feb. 2013. DOI: 10.1109/TRO.2012.2222272. + + For more information on constrained sampling-based planning using atlas-based methods, see the following + review paper. The section on atlas-based methods cites most of the relevant literature. + + Z. Kingston, M. Moll, and L. E. Kavraki, “Sampling-Based Methods for Motion Planning with Constraints,” + Annual Review of Control, Robotics, and Autonomous Systems, 2018. DOI: + 10.1146/annurev-control-060117-105226 + [PDF]. + */ + + /** \brief ConstrainedStateSpace encapsulating a planner-agnostic atlas + * algorithm for planning on a constraint manifold. */ + class AtlasStateSpace : public ConstrainedStateSpace + { + public: + using AtlasChartBiasFunction = std::function; + using NNElement = std::pair; + + /** \brief A state in an atlas represented as a real vector in + * ambient space and a chart that it belongs to. */ + class StateType : public ConstrainedStateSpace::StateType + { + public: + /** \brief Construct state of size \a n. */ + StateType(const ConstrainedStateSpace *space) : ConstrainedStateSpace::StateType(space) + { + } + + /** \brief Get the chart this state is on. */ + AtlasChart *getChart() const + { + return chart_; + } + + /** \brief Set the chart \a c for the state. */ + void setChart(AtlasChart *c) const + { + chart_ = c; + } + + private: + /** \brief Chart owning the state. */ + mutable AtlasChart *chart_{nullptr}; + }; + + /** \brief Construct an atlas with the specified dimensions. */ + AtlasStateSpace(const StateSpacePtr &ambientSpace, const ConstraintPtr &constraint, bool separate = true); + + /** \brief Destructor. */ + ~AtlasStateSpace() override; + + /** \brief Reset the space (except for anchor charts). */ + void clear() override; + + /** \brief Allocate the default state sampler for this space. */ + StateSamplerPtr allocDefaultStateSampler() const override + { + return std::make_shared(this); + } + + /** \brief Allocate the previously set state sampler for this space. */ + StateSamplerPtr allocStateSampler() const override + { + return std::make_shared(this); + } + + void copyState(State *destination, const State *source) const override + { + ConstrainedStateSpace::copyState(destination, source); + destination->as()->setChart(source->as()->getChart()); + } + + /** \brief Allocate a new state in this space. */ + State *allocState() const override + { + return new StateType(this); + } + + /** @name Getters and Setters + @{ */ + + /** \brief Set \a epsilon, the maximum permissible distance between + * a point in the validity region of a chart and its projection onto + * the manifold. Default 0.1. */ + void setEpsilon(double epsilon) + { + if (epsilon <= 0) + throw ompl::Exception("ompl::base::AtlasStateSpace::setEpsilon(): " + "epsilon must be positive."); + epsilon_ = epsilon; + } + + /** \brief Set \a rho, the maximum radius for which a chart is + * valid. Default 0.1. */ + void setRho(double rho) + { + if (rho <= 0) + throw ompl::Exception("ompl::base::AtlasStateSpace::setRho(): " + "rho must be positive."); + rho_ = rho; + rho_s_ = rho_ / std::pow(1 - exploration_, 1.0 / k_); + } + + /** \brief Set \a alpha, the maximum permissible angle between the + * chart and the manifold inside the validity region of the + * chart. Must be within the range (0, pi/2). Default pi/16. */ + void setAlpha(double alpha) + { + if (alpha <= 0 || alpha >= boost::math::constants::pi() / 2.) + throw ompl::Exception("ompl::base::AtlasStateSpace::setAlpha(): " + "alpha must be in (0, pi/2)."); + cos_alpha_ = std::cos(alpha); + } + + /** \brief Set the \a exploration parameter, which tunes the balance + * of refinement (sampling within known regions) and exploration + * (sampling on the frontier). Valid values are in the range [0,1), + * where 0 is all refinement, and 1 is all exploration. Default + * 0.5. */ + void setExploration(double exploration) + { + if (exploration >= 1) + throw ompl::Exception("ompl::base::AtlasStateSpace::setExploration(): " + "exploration must be in [0, 1)."); + exploration_ = exploration; + + // Update sampling radius + setRho(rho_); + } + + /** \brief Sometimes manifold traversal creates many charts. This + * parameter limits the number of charts that can be created during + * one traversal. Default 200. */ + void setMaxChartsPerExtension(unsigned int charts) + { + maxChartsPerExtension_ = charts; + } + + /** \brief Sets bias function for sampling. */ + void setBiasFunction(const AtlasChartBiasFunction &biasFunction) + { + biasFunction_ = biasFunction; + } + + /** \brief Sets whether the atlas should separate charts or not. */ + void setSeparated(bool separate) + { + separate_ = separate; + } + + /** \brief Sets the backoff factor in manifold traversal factor. */ + void setBackoff(double backoff) + { + backoff_ = backoff; + } + + /** \brief Get epsilon. */ + double getEpsilon() const + { + return epsilon_; + } + + /** \brief Get rho. */ + double getRho() const + { + return rho_; + } + + /** \brief Get alpha. */ + double getAlpha() const + { + return std::acos(cos_alpha_); + } + + /** \brief Get the exploration parameter. */ + double getExploration() const + { + return exploration_; + } + + /** \brief Get the sampling radius. */ + double getRho_s() const + { + return rho_s_; + } + + /** \brief Get the maximum number of charts to create in one pass. */ + unsigned int getMaxChartsPerExtension() const + { + return maxChartsPerExtension_; + } + + /** \brief Returns whether the atlas is separating charts or not. */ + bool isSeparated() const + { + return separate_; + } + + /** \brief Return the number of charts currently in the atlas. */ + std::size_t getChartCount() const + { + return charts_.size(); + } + + /** \brief Returns the current backoff factor used in manifold traversal. */ + double getBackoff() const + { + return backoff_; + } + + /** @} */ + + /** @name Atlas Chart Management + @{ */ + + /** \brief Create a new chart for the atlas, centered at \a xorigin, + * which should be on the manifold. Returns nullptr upon failure. */ + AtlasChart *newChart(const StateType *state) const; + + /** \brief Pick a chart at random. */ + AtlasChart *sampleChart() const; + + /** \brief Find the chart to which \a x belongs. Returns nullptr if + * no chart found. Assumes \a x is already on the manifold. */ + AtlasChart *owningChart(const StateType *state) const; + + /** \brief Wrapper to return chart \a state belongs to. Will attempt + * to initialize new chart if \a state does not belong to one. If \a + * force is true, this routine will reinitialize the chart that the + * state should be on. If \a created is not null, it will be set to + * true if a new chart is created. */ + AtlasChart *getChart(const StateType *state, bool force = false, bool *created = nullptr) const; + + /** @} */ + + /** @name Constrained Planning + @{ */ + + /** \brief Wrapper for newChart(). Charts created this way will + * persist through calls to clear(). + * \throws ompl::Exception if manifold seems degenerate here. */ + AtlasChart *anchorChart(const State *state) const; + + /** \brief Traverse the manifold from \a from toward \a to. Returns + * true if we reached \a to, and false if we stopped early for any + * reason, such as a collision or traveling too far. No collision + * checking is performed if \a interpolate is true. If \a geodesic + * is not nullptr, the sequence of intermediates is saved to it, + * including a copy of \a from, as well as the final state, which is + * a copy of \a to if we reached \a to. Caller is responsible for + * freeing states returned in \a geodesic.*/ + bool discreteGeodesic(const State *from, const State *to, bool interpolate = false, + std::vector *geodesic = nullptr) const override; + + /** @} */ + + /** @name Statistics and Visualization + @{ */ + + /** \brief Estimate what percentage of atlas charts do not have + * fully formed polytope boundaries, and are therefore on the + * frontier. */ + double estimateFrontierPercent() const; + + /** \brief Write a mesh representation of the atlas to a stream. */ + void printPLY(std::ostream &out) const; + + /** @} */ + + protected: + /** \brief Set of states on which there are anchored charts. */ + mutable std::vector anchors_; + + /** \brief Set of charts. */ + mutable std::vector charts_; + + /** \brief PDF of charts according to a bias function. */ + mutable PDF chartPDF_; + + /** \brief Set of chart centers and indices, accessible by + * nearest-neighbor queries to the chart centers. */ + mutable NearestNeighborsGNAT chartNN_; + + /** @name Tunable Parameters + @{ */ + + /** \brief Maximum distance between a chart and the manifold inside its validity region. */ + double epsilon_{ompl::magic::ATLAS_STATE_SPACE_EPSILON}; + + /** \brief Maximum radius of chart validity region. */ + double rho_; + + /** \brief Cosine of the maximum angle between a chart and the manifold inside its validity region. */ + double cos_alpha_; + + /** \brief Balance between explorationa and refinement. */ + double exploration_; + + /** \brief Sampling radius within a chart. Inferred from rho and exploration parameters. */ + mutable double rho_s_; + + /** \brief Step size reduction factor during manifold traversal. */ + double backoff_{ompl::magic::ATLAS_STATE_SPACE_BACKOFF}; + + /** \brief Maximum number of charts that can be created in one manifold traversal. */ + unsigned int maxChartsPerExtension_{ompl::magic::ATLAS_STATE_SPACE_MAX_CHARTS_PER_EXTENSION}; + + /** @} */ + + /** \brief Function to bias chart sampling */ + AtlasChartBiasFunction biasFunction_; + + /** \brief Enable or disable halfspace separation of the charts. */ + bool separate_; + + /** \brief Random number generator. */ + mutable RNG rng_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ConstrainedStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ConstrainedStateSpace.h new file mode 100644 index 00000000..5a458e6c --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ConstrainedStateSpace.h @@ -0,0 +1,346 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston */ + +#ifndef OMPL_BASE_SPACES_CONSTRAINED_STATE_SPACE_ +#define OMPL_BASE_SPACES_CONSTRAINED_STATE_SPACE_ + +#include "ompl/base/Constraint.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/MotionValidator.h" +#include "ompl/base/spaces/WrapperStateSpace.h" +#include "ompl/base/SpaceInformation.h" + +#include + +namespace ompl +{ + namespace magic + { + static const double CONSTRAINED_STATE_SPACE_DELTA = 0.05; + static const double CONSTRAINED_STATE_SPACE_LAMBDA = 2.0; + } // namespace magic + + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ConstrainedStateSpace */ + OMPL_CLASS_FORWARD(ConstrainedStateSpace); + /// @endcond + + /** \brief Constrained configuration space specific implementation of + * checkMotion() that uses discreteGeodesic(). */ + class ConstrainedMotionValidator : public MotionValidator + { + public: + /** \brief Constructor. */ + ConstrainedMotionValidator(SpaceInformation *si); + + /** \brief Constructor. */ + ConstrainedMotionValidator(const SpaceInformationPtr &si); + + /** \brief Return whether we can step from \a s1 to \a s2 along the + * manifold without collision. */ + bool checkMotion(const State *s1, const State *s2) const override; + + /** \brief Return whether we can step from \a s1 to \a s2 along the + * manifold without collision. If not, return the last valid state + * and its interpolation parameter in \a lastValid. \note The + * interpolation parameter will not likely reproduce the last valid + * state if used in interpolation since the distance between the + * last valid state and \a s2 is estimated using the ambient + * metric. */ + bool checkMotion(const State *s1, const State *s2, std::pair &lastValid) const override; + + protected: + /** \brief Space in which we check motion. */ + const ConstrainedStateSpace &ss_; + }; + + /** + @anchor gConstrained + @par Short Description + ConstrainedStateSpace encapsulates the idea of decoupled constrained planning, where the planner and + constraint satisfaction methodology are separated. Core to this idea is the augmentation of a state space, + rather than the augmentation of a planner. In OMPL, this is implemented as the ConstrainedStateSpace and its + concrete implementations: ProjectedStateSpace for projection-based constraint satisfaction, AtlasStateSpace + for atlas-based manifold approximation, and TangentBundleStateSpace for a lazy atlas-based approach. + + The core benefit of this method is that there is no additional work to make a sampling-based planner plan + with constraints (in this case, a differentiable function of a state, implemented in Constraint), enabling + mix-and-matching of planners with constraint methodologies, e.g., KPIECE1 with TangentBundleStateSpace, or + RRT* with ProjectedStateSpace, and so on. + + See \ref constrainedPlanning for more details. + + @par External Documentation + The following paper describes the idea of decoupled constrained planning, as implemented in OMPL. + + Zachary Kingston, Mark Moll, and Lydia E. Kavraki, Exploring Implicit Spaces for Constrained Sampling-Based + Planning, _International Journal of Robotics Research,_ 38(10–11):1151–1178, September 2019. + DOI: 10.1177/0278364919868530 + PrePrint: + [PDF] + + For more information on constrained sampling-based planning in general, see the following review paper. The + sections on projection- and atlas-based planning describe the methods used in the ProjectedStateSpace, + AtlasStateSpace, and TangentBundleStateSpace. + + Z. Kingston, M. Moll, and L. E. Kavraki, “Sampling-Based Methods for Motion Planning with Constraints,” + Annual Review of Control, Robotics, and Autonomous Systems, 2018. DOI: + 10.1146/annurev-control-060117-105226 + [PDF]. + */ + + /** \brief A StateSpace that has a \a Constraint imposed upon it. + * Underlying space functions are passed to the ambient space, and the + * constraint is used to inform any manifold related operations. + * setSpaceInformation() must be called in order for collision checking + * to be done in tandem with manifold traversal. */ + class ConstrainedStateSpace : public WrapperStateSpace + { + public: + /** \brief Flags used in a bit mask for constrained state space + * sanity checks, constraintSanityChecks(). */ + enum SanityChecks + { + /** \brief Check whether state samplers return constraint + * satisfying samples. */ + CONSTRAINED_STATESPACE_SAMPLERS = (1 << 1), + + /** \brief Check whether discrete geodesics satisfy the + * constraint at all points. */ + CONSTRAINED_STATESPACE_GEODESIC_SATISFY = (1 << 2), + + /** \brief Check whether discrete geodesics keep lambda_ * + * delta_ continuity. */ + CONSTRAINED_STATESPACE_GEODESIC_CONTINUITY = (1 << 3), + + /** \brief Check whether geodesicInterpolate(...) returns + * constraint satisfying states. */ + CONSTRAINED_STATESPACE_GEODESIC_INTERPOLATE = (1 << 4), + + /** \brief Check if the constraint's numerical Jacobian + * approximates its provided Jacobian. */ + CONSTRAINED_STATESPACE_JACOBIAN = (1 << 5) + }; + + /** \brief A State in a ConstrainedStateSpace, represented as a + * dense real vector of values. For convenience and efficiency of + * various Constraint related operations, this State inherits from + * Eigen::Map, mapping the underlying dense double + * vector into an Eigen::VectorXd. Note that this state type + * inherits from WrapperStateSpace::StateType, and as such the + * underlying state can be accessed by getState(). */ + class StateType : public WrapperStateSpace::StateType, public Eigen::Map + { + public: + /** \brief Constructor. Requires \a space to setup information about underlying state. */ + StateType(const ConstrainedStateSpace *space) + : WrapperStateSpace::StateType(space->getSpace()->allocState()) + , Eigen::Map(space->getValueAddressAtIndex(this, 0), space->getDimension()) + { + } + + /** \brief Copy the contents from a vector into this state. Uses + * the underlying copy operator used by Eigen for dense + * vectors. */ + void copy(const Eigen::Ref &other) + { + // Explicitly cast and call `=` on the state as an + // Eigen::Map<...>. This copies the other. + static_cast *>(this)->operator=(other); + } + }; + + /** \brief Construct a constrained space from an \a ambientSpace and + * a \a constraint. */ + ConstrainedStateSpace(const StateSpacePtr &ambientSpace, const ConstraintPtr &constraint); + + /** @name State Space Related Operations + @{ */ + + /** \brief Returns false as the implicit constrained configuration + * space defined by the constraint is not metric with respect to the + * ambient configuration space's metric. */ + bool isMetricSpace() const override + { + return false; + } + + /** \brief Sets the space information for this state space. Required + * for collision checking in manifold traversal. */ + void setSpaceInformation(SpaceInformation *si); + + /** \brief Final setup for the space. */ + void setup() override; + + /** \brief Clear any allocated memory from the state space. */ + virtual void clear(); + + /** \brief Allocate a new state in this space. */ + State *allocState() const override; + + /** \brief Do some sanity checks relating to discrete geodesic + computation and constraint satisfaction. See SanityChecks flags. */ + void constrainedSanityChecks(unsigned int flags) const; + + /** \brief Perform both constrained and regular sanity checks. */ + void sanityChecks() const override; + + /** \brief Return the valid segment count on the manifold, as valid + * segment count is determined by \e delta_ and \e lambda_. */ + unsigned int validSegmentCount(const State *s1, const State *s2) const override + { + return distance(s1, s2) * (1. / delta_) * lambda_; + } + + /** @} */ + + /** @name Constrained Planning + @{ */ + + /** \brief Find a state between \a from and \a to around time \a t, + * where \a t = 0 is \a from, and \a t = 1 is the final state + * reached by discreteGeodesic(\a from, \a to, true, ...), which may + * not be \a to. State returned in \a state. */ + void interpolate(const State *from, const State *to, double t, State *state) const override; + + /** \brief Traverse the manifold from \a from toward \a to. Returns + * true if we reached \a to, and false if we stopped early for any + * reason, such as a collision or traveling too far. No collision + * checking is performed if \a interpolate is true. If \a geodesic + * is not nullptr, the sequence of intermediates is saved to it, + * including a copy of \a from, as well as the final state, which is + * a copy of \a to if we reached \a to. Caller is responsible for + * freeing states returned in \a geodesic. Needs to be implemented + * by any constrained state space. */ + virtual bool discreteGeodesic(const State *from, const State *to, bool interpolate = false, + std::vector *geodesic = nullptr) const = 0; + + /** \brief Like interpolate(...), but interpolates between + * intermediate states already supplied in \a stateList from a + * previous call to discreteGeodesic(..., \a geodesic). The + * \a from and \a to states are the first and last elements \a + * stateList. Returns a pointer to a state in \a geodesic. */ + virtual State *geodesicInterpolate(const std::vector &geodesic, double t) const; + + /** @} */ + + /** @name Setters and Getters + @{ */ + + /** \brief Set \a delta, the step size for traversing the manifold + * and collision checking. Default defined by + * ompl::magic::CONSTRAINED_STATE_SPACE_DELTA. */ + void setDelta(double delta); + + /** \brief Set \a lambda, where lambda * distance(x, y) is the + * maximum length of the geodesic x to y. Additionally, lambda * + * delta is the greatest distance a point can diverge from its + * previous step, to preserve continuity. Must be greater than 1. */ + void setLambda(double lambda) + { + if (lambda <= 1) + throw ompl::Exception("ompl::base::AtlasStateSpace::setLambda(): " + "lambda must be > 1."); + lambda_ = lambda; + } + + /** \brief Get delta, the step size across the manifold. */ + double getDelta() const + { + return delta_; + } + + /** \brief Get lambda (see setLambda()). */ + double getLambda() const + { + return lambda_; + } + + /** \brief Returns the dimension of the ambient space. */ + unsigned int getAmbientDimension() const + { + return n_; + } + + /** \brief Returns the dimension of the manifold. */ + unsigned int getManifoldDimension() const + { + return k_; + } + + /** \brief Returns the constraint that defines the underlying manifold. */ + const ConstraintPtr getConstraint() const + { + return constraint_; + } + + /** @} */ + + protected: + /** \brief SpaceInformation associated with this space. Required + * for early collision checking in manifold traversal. */ + SpaceInformation *si_{nullptr}; + + /** \brief Constraint function that defines the manifold. */ + const ConstraintPtr constraint_; + + /** \brief Ambient space dimension. */ + const unsigned int n_; + + /** \brief Manifold dimension. */ + const unsigned int k_; + + /** \brief Step size when traversing the manifold and collision checking. */ + double delta_; + + /** \brief Manifold traversal from x to y is stopped if accumulated + * distance is greater than d(x,y) times this. Additionally, if d(x, + * y) is greater than lambda * delta between two points, search is + * discontinued. */ + double lambda_{ompl::magic::CONSTRAINED_STATE_SPACE_LAMBDA}; + + /** \brief Whether setup() has been called. */ + bool setup_{false}; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ProjectedStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ProjectedStateSpace.h new file mode 100644 index 00000000..e3b6d218 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ProjectedStateSpace.h @@ -0,0 +1,142 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2017, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston */ + +#ifndef OMPL_BASE_SPACES_PROJECTED_STATE_SPACE_ +#define OMPL_BASE_SPACES_PROJECTED_STATE_SPACE_ + +#include "ompl/base/MotionValidator.h" +#include "ompl/base/PlannerData.h" +#include "ompl/base/StateSampler.h" +#include "ompl/base/ValidStateSampler.h" +#include "ompl/base/Constraint.h" +#include "ompl/base/spaces/RealVectorStateSpace.h" +#include "ompl/base/spaces/constraint/ConstrainedStateSpace.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::ProjectedStateSpace */ + OMPL_CLASS_FORWARD(ProjectedStateSpace); + /// @endcond + + /** \brief StateSampler for use for a projection-based state space. */ + class ProjectedStateSampler : public WrapperStateSampler + { + public: + /** \brief Constructor. */ + ProjectedStateSampler(const ProjectedStateSpace *space, StateSamplerPtr sampler); + + /** \brief Sample a state uniformly in ambient space and project to + * the manifold. Return sample in \a state. */ + void sampleUniform(State *state) override; + + /** \brief Sample a state uniformly from the ball with center \a + * near and radius \a distance in ambient space and project to the + * manifold. Return sample in \a state. */ + void sampleUniformNear(State *state, const State *near, double distance) override; + + /** \brief Sample a state uniformly from a normal distribution with + given \a mean and \a stdDev in ambient space and project to the + manifold. Return sample in \a state. */ + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + protected: + /** \brief Constraint. */ + const ConstraintPtr constraint_; + }; + + /** + @anchor gProject + @par Short Description + ProjectedStateSpace implements a projection-based methodology for constrained sampling-based planning, where + points in ambient space are \e projected onto the constraint manifold via a projection operator, which in + this case is implemented as a Newton's method within the Constraint. + + @par External Documentation + For more information on constrained sampling-based planning using projection-based methods, see the following + review paper. The section on projection-based methods cites most of the relevant literature. + + Z. Kingston, M. Moll, and L. E. Kavraki, “Sampling-Based Methods for Motion Planning with Constraints,” + Annual Review of Control, Robotics, and Autonomous Systems, 2018. DOI: + 10.1146/annurev-control-060117-105226 + [PDF]. + */ + + /** \brief ConstrainedStateSpace encapsulating a projection-based + * methodology for planning with constraints. */ + class ProjectedStateSpace : public ConstrainedStateSpace + { + public: + /** \brief Construct an atlas with the specified dimensions. */ + ProjectedStateSpace(const StateSpacePtr &ambientSpace, const ConstraintPtr &constraint) + : ConstrainedStateSpace(ambientSpace, constraint) + { + setName("Projected" + space_->getName()); + } + + /** \brief Destructor. */ + ~ProjectedStateSpace() override = default; + + /** \brief Allocate the default state sampler for this space. */ + StateSamplerPtr allocDefaultStateSampler() const override + { + return std::make_shared(this, space_->allocDefaultStateSampler()); + } + + /** \brief Allocate the previously set state sampler for this space. */ + StateSamplerPtr allocStateSampler() const override + { + return std::make_shared(this, space_->allocStateSampler()); + } + + /** \brief Traverse the manifold from \a from toward \a to. Returns + * true if we reached \a to, and false if we stopped early for any + * reason, such as a collision or traveling too far. No collision + * checking is performed if \a interpolate is true. If \a geodesic + * is not nullptr, the sequence of intermediates is saved to it, + * including a copy of \a from, as well as the final state, which is + * a copy of \a to if we reached \a to. Caller is responsible for + * freeing states returned in \a geodesic.*/ + bool discreteGeodesic(const State *from, const State *to, bool interpolate = false, + std::vector *geodesic = nullptr) const override; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/TangentBundleStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/TangentBundleStateSpace.h new file mode 100644 index 00000000..3c33e2e4 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/TangentBundleStateSpace.h @@ -0,0 +1,118 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Zachary Kingston */ + +#ifndef OMPL_BASE_SPACES_TANGENTBUNDLE_STATE_SPACE_ +#define OMPL_BASE_SPACES_TANGENTBUNDLE_STATE_SPACE_ + +#include "ompl/base/spaces/constraint/AtlasStateSpace.h" + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::base::TangentBundleStateSpace */ + OMPL_CLASS_FORWARD(TangentBundleStateSpace); + /// @endcond + + /** + @anchor gTangentBundle + @par Short Description + TangentBundleStateSpace implements a lazy atlas-based methodology for constrained sampling-based planning, + where the underlying constraint manifold is locally parameterized by \e charts (AtlasChart). The underlying + constraint manifold can then be sampled and explored using the collection of these charts (an \e atlas). The + difference between TangentBundleStateSpace and AtlasStateSpace is three-fold: TangentBundleStateSpace takes a + lazy approach to evaluating the constraint function when traversing the manifold, TangentBundleStateSpace + uses biased sampling for selected charts by default, and TangentBundleStateSpace does not use halfspace + separation of charts. + + @par External Documentation + This state space is inspired by the work on Tangent Bundle RRT. + + B. Kim, T. T. Um, C. Suh, and F. C. Park, "Tangent bundle RRT: A randomized algorithm for constrained motion + planning," Robotica 34.1 (2016): 202-225. DOI: + 10.1017/S0263574714001234. + + For more information on constrained sampling-based planning using atlas-based methods, see the following + review paper. The section on atlas-based methods cites most of the relevant literature. + + Z. Kingston, M. Moll, and L. E. Kavraki, “Sampling-Based Methods for Motion Planning with Constraints,” + Annual Review of Control, Robotics, and Autonomous Systems, 2018. DOI: + 10.1146/annurev-control-060117-105226 + [PDF]. + */ + + /** \brief ConstrainedStateSpace encapsulating a planner-agnostic lazy + * atlas algorithm for planning on a constraint manifold. */ + class TangentBundleStateSpace : public AtlasStateSpace + { + public: + TangentBundleStateSpace(const StateSpacePtr &ambientSpace, const ConstraintPtr &constraint); + + /** \brief Do sanity checks, minus geodesic constraint + * satisfiability (as this is a lazy method). */ + void sanityChecks() const override; + + /** \brief Traverse the manifold from \a from toward \a to. Returns + * true if we reached \a to, and false if we stopped early for any + * reason, such as a collision or traveling too far. No collision + * checking is performed if \a interpolate is true. If \a geodesic + * is not nullptr, the sequence of intermediates is saved to it, + * including a copy of \a from, as well as the final state, which is + * a copy of \a to if we reached \a to. Caller is responsible for + * freeing states returned in \a geodesic.*/ + bool discreteGeodesic(const State *from, const State *to, bool interpolate = false, + std::vector *geodesic = nullptr) const override; + + /** \brief Like interpolate(...), but interpolates between + * intermediate states already supplied in \a stateList from a + * previous call to discreteGeodesic(..., \a geodesic). The \a from + * and \a to states are the first and last elements \a stateList. + * Returns a pointer to a state in \a geodesic. As + * TangentBundleStateSpace employs a lazy approach to manifold + * traversal, additional fix-up is required to generate a state that + * satisfies constraints. */ + State *geodesicInterpolate(const std::vector &geodesic, double t) const override; + + /** \brief Reproject a state onto the surface of the manifold. Returns true if projection was successful, + * and the new state is valid. */ + bool project(State *state) const; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/KleinBottleStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/KleinBottleStateSpace.h new file mode 100644 index 00000000..b8768c2a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/KleinBottleStateSpace.h @@ -0,0 +1,134 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, + * Max Planck Institute for Intelligent Systems (MPI-IS). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the MPI-IS nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SPACES_KLEINBOTTLE_STATE_SPACE_ +#define OMPL_BASE_SPACES_KLEINBOTTLE_STATE_SPACE_ + +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief State sampler for the Klein bottle state space */ + class KleinBottleStateSampler : public StateSampler + { + public: + KleinBottleStateSampler(const StateSpace *space); + + void sampleUniform(State *state) override; + + void sampleUniformNear(State *state, const State *near, double distance) override; + + void sampleGaussian(State *state, const State *mean, double stdDev) override; + + private: + /** \brief Constant of maximum norm gradient of surface (do not change). + * Estimated by taking the upper bound over 10k samples. */ + const double gMax_{4.1455}; + }; + + /** \brief The Klein bottle is a 2-dimensional non-orientable surface. + * In this class, we implement a 3-dimensional immersion of the + * Bottle. */ + class KleinBottleStateSpace : public CompoundStateSpace + { + public: + /** \brief The definition of a state (u,v) in the Klein bottle state + * space. A state is represented as a cylinder with height u in the + * interval [0, Pi] and + * angle v in the interval [-Pi, Pi] as in the discussion + * here: https://en.wikipedia.org/wiki/Klein_bottle#Construction + * + * This cylinder is then glued together (mapped) internally to provide + * correct distance and interpolation functions. */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + /** \brief Access U, the height of the cylinder */ + double getU() const + { + return as(0)->values[0]; + } + /** \brief Access V, the angle of the cylinder */ + double getV() const + { + return as(1)->value; + } + + /** \brief Set U, the height of the cylinder */ + void setU(double u) + { + as(0)->values[0] = u; + } + /** \brief Set V, the angle of the cylinder */ + void setV(double v) + { + as(1)->value = v; + } + void setUV(double u, double v) + { + setU(u); + setV(v); + } + }; + + KleinBottleStateSpace(); + + ~KleinBottleStateSpace() override = default; + + StateSamplerPtr allocDefaultStateSampler() const override; + + double distance(const State *state1, const State *state2) const override; + + void interpolate(const State *from, const State *to, double t, State *state) const override; + + State *allocState() const override; + + /* \brief Convert a state to a 3D vector to visualize the state + * space. */ + Eigen::Vector3f toVector(const State *state) const; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/MobiusStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/MobiusStateSpace.h new file mode 100644 index 00000000..22cf94ab --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/MobiusStateSpace.h @@ -0,0 +1,109 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, + * Max Planck Institute for Intelligent Systems (MPI-IS). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the MPI-IS nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SPACES_MOBIUS_STATE_SPACE_ +#define OMPL_BASE_SPACES_MOBIUS_STATE_SPACE_ + +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief The Mobius strip is a 2-dimensional non-orientable surface. + * */ + class MobiusStateSpace : public CompoundStateSpace + { + public: + /** \brief The definition of a state (u,v) in the Mobius strip state + * space. + * The variable u is the position on the center circle in the interval [-Pi, Pi] + * The variable v is the position along the width in the interval [-intervalMax, intervalMax] + * */ + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + double getU() const + { + return as(0)->value; + } + double getV() const + { + return as(1)->values[0]; + } + + void setU(double u) + { + as(0)->value = u; + } + void setV(double v) + { + as(1)->values[0] = v; + } + void setUV(double u, double v) + { + setU(u); + setV(v); + } + }; + + MobiusStateSpace(double intervalMax = 1.0, double radius = 1.0); + + virtual ~MobiusStateSpace() override = default; + + virtual double distance(const State *state1, const State *state2) const override; + + virtual void interpolate(const State *from, const State *to, double t, State *state) const override; + + virtual State *allocState() const override; + + /* \brief Convert a state to a 3D vector to visualize the state + * space. */ + Eigen::Vector3f toVector(const State *state) const; + + private: + double radius_{1.0}; // radius of inner circle + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/SphereStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/SphereStateSpace.h new file mode 100644 index 00000000..fae21d9f --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/SphereStateSpace.h @@ -0,0 +1,120 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, + * Max Planck Institute for Intelligent Systems (MPI-IS). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the MPI-IS nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SPACES_SPHERE_STATE_SPACE_ +#define OMPL_BASE_SPACES_SPHERE_STATE_SPACE_ + +#include +#include +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief State sampler for the sphere state space */ + class SphereStateSampler : public ompl::base::StateSampler + { + public: + SphereStateSampler(const StateSpace *space); + + void sampleUniform(State *state) override; + + void sampleUniformNear(State *state, const State *near, double distance) override; + + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + class SphereStateSpace : public CompoundStateSpace + { + public: + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + double getTheta() const + { + return as(0)->value; + } + double getPhi() const + { + return as(1)->values[0]; + } + + void setTheta(double theta) + { + as(0)->value = theta; + } + void setPhi(double phi) + { + as(1)->values[0] = phi; + } + void setThetaPhi(double theta, double phi) + { + setTheta(theta); + setPhi(phi); + } + }; + + SphereStateSpace(double radius = 1.0); + + virtual ~SphereStateSpace() override = default; + + virtual StateSamplerPtr allocDefaultStateSampler() const override; + + virtual double getMeasure() const override; + + virtual double distance(const State *state1, const State *state2) const override; + + virtual State *allocState() const override; + + double getMaximumExtent() const override; + + /* \brief Convert a state to a 3D vector to visualize the state + * space. */ + Eigen::Vector3f toVector(const State *state) const; + + protected: + double radius_{1.0}; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/TorusStateSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/TorusStateSpace.h new file mode 100644 index 00000000..f88964b3 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/TorusStateSpace.h @@ -0,0 +1,120 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2021, + * Max Planck Institute for Intelligent Systems (MPI-IS). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the MPI-IS nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Andreas Orthey */ + +#ifndef OMPL_BASE_SPACES_TORUS_STATE_SPACE_ +#define OMPL_BASE_SPACES_TORUS_STATE_SPACE_ + +#include +#include + +namespace ompl +{ + namespace base + { + /** \brief State sampler for the torus state space */ + class TorusStateSampler : public StateSampler + { + public: + TorusStateSampler(const StateSpace *space); + + void sampleUniform(State *state) override; + + void sampleUniformNear(State *state, const State *near, double distance) override; + + void sampleGaussian(State *state, const State *mean, double stdDev) override; + }; + + class TorusStateSpace : public CompoundStateSpace + { + public: + class StateType : public CompoundStateSpace::StateType + { + public: + StateType() = default; + + double getS1() const + { + return as(0)->value; + } + double getS2() const + { + return as(1)->value; + } + + void setS1(double s) + { + as(0)->value = s; + } + void setS2(double s) + { + as(1)->value = s; + } + void setS1S2(double s, double t) + { + setS1(s); + setS2(t); + } + }; + + TorusStateSpace(double majorRadius = 1, double minorRadius = 0.5); + + virtual ~TorusStateSpace() override = default; + + StateSamplerPtr allocDefaultStateSampler() const override; + + double distance(const State *state1, const State *state2) const override; + + State *allocState() const override; + + double getMajorRadius() const; + + double getMinorRadius() const; + + /* \brief Convert a state to a 3D vector to visualize the state + * space. */ + Eigen::Vector3f toVector(const State *state) const; + + private: + double majorRadius_; + + double minorRadius_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/CostConvergenceTerminationCondition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/CostConvergenceTerminationCondition.h new file mode 100644 index 00000000..8cc083ba --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/CostConvergenceTerminationCondition.h @@ -0,0 +1,83 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, PickNik LLC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the PickNik LLC nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Henning Kayser, Mark Moll */ + +#ifndef OMPL_BASE_COST_CONVERGENCE_TERMINATION_CONDITION_ +#define OMPL_BASE_COST_CONVERGENCE_TERMINATION_CONDITION_ + +#include "ompl/base/PlannerTerminationCondition.h" + +namespace ompl +{ + namespace base + { + /// \brief: A termination condition for stopping an optimizing planner based on cost convergence + class CostConvergenceTerminationCondition : public PlannerTerminationCondition + { + public: + /// \brief Constructor + /// \param pdef Problem definition, needed to get access to the optimization + /// objective and to set a callback to get intermediate solutions. + /// \param solutionsWindow Minimum number of solutions to use in deciding + /// whether a planner has converged. + /// \param epsilon Threshold to consider for convergence. This should be a positive number close to 0. + /// If the cumulative moving average does not change by a relative fraction of epsilon after a new better + /// solution is found, convergence has been reached and a planner should terminate.. + CostConvergenceTerminationCondition(ProblemDefinitionPtr &pdef, size_t solutionsWindow = 10, + double epsilon = 0.1); + + // Compute the running average cost of the last solutions (solutionWindow) + // and terminate if the cost of a new solution is worse than + // convergenceThreshold times the average cost. + void processNewSolution(const Cost solutionCost); + + private: + /// Shared pointer to problem definition. + ProblemDefinitionPtr pdef_; + /// Cumulative moving average of solutions found so far. + double averageCost_{0.}; + /// Number of solutions found so far. + size_t solutions_{0}; + + /// Minimum number of solutions needed to decide whether the planner has converged. + const size_t solutionsWindow_; + /// If an update to the cumulative moving average changes it by less than an epsilon fraction, convergence + /// has been reached. + const double epsilon_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/IterationTerminationCondition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/IterationTerminationCondition.h new file mode 100644 index 00000000..f7758c8a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/IterationTerminationCondition.h @@ -0,0 +1,79 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2019, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#include "ompl/base/PlannerTerminationCondition.h" + +#ifndef OMPL_BASE_ITERATION_TERMINATION_CONDITION_ +#define OMPL_BASE_ITERATION_TERMINATION_CONDITION_ + +namespace ompl +{ + namespace base + { + /** \brief A class to run a planner for a specific number of iterations. Casts to a PTC for use with + * Planner::solve */ + class IterationTerminationCondition + { + public: + /** \brief Construct a termination condition that can be evaluated numIterations times before returning + * true. */ + IterationTerminationCondition(unsigned int numIterations); + + /** \brief Increment the number of times eval has been called and check if the planner should now terminate. + */ + bool eval(); + + /** \brief Reset the number of times the IterationTeriminationCondition has been called. */ + void reset(); + + /** \brief Cast to a PlannerTerminationCondition */ + operator PlannerTerminationCondition(); + + unsigned int getTimesCalled() const + { + return timesCalled_; + } + + private: + /** \brief The max number of iterations the condition can be called before returning true. */ + unsigned int maxCalls_; + /** \brief The number of times called so far.*/ + unsigned int timesCalled_; + }; + } // namespace base +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/config.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/config.h new file mode 100644 index 00000000..83c37686 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/config.h @@ -0,0 +1,60 @@ +/********************************************************************* +* Software License Agreement (BSD License) +* +* Copyright (c) 2010, Rice University. +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above +* copyright notice, this list of conditions and the following +* disclaimer in the documentation and/or other materials provided +* with the distribution. +* * Neither the name of the Rice University nor the names of its +* contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONFIG_ +#define OMPL_CONFIG_ + +/** \brief The ompl version */ +#define OMPL_VERSION "2.0.2" + +#define OMPL_MAJOR_VERSION 2 +#define OMPL_MINOR_VERSION 0 +#define OMPL_PATCH_VERSION 2 + +#define OMPL_VERSION_VALUE ( OMPL_MAJOR_VERSION * 1000000 \ + + OMPL_MINOR_VERSION * 1000 \ + + OMPL_PATCH_VERSION) + +/** \brief Whether FLANN is installed */ +#define OMPL_HAVE_FLANN 0 + +/** \brief Whether SPOT is installed */ +#define OMPL_HAVE_SPOT 0 + +/** \brief Whether Numpy and Boost.Numpy are installed */ +#define OMPL_HAVE_NUMPY 0 + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/Control.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/Control.h new file mode 100644 index 00000000..f0f554d5 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/Control.h @@ -0,0 +1,122 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_CONTROL_ +#define OMPL_CONTROL_CONTROL_ + +#include + +namespace ompl +{ + namespace control + { + /** \brief Definition of an abstract control */ + class Control + { + private: + /** \brief Disable copy-constructor */ + Control(const Control &) = delete; + + /** \brief Disable copy operator */ + const Control &operator=(const Control &) = delete; + + protected: + Control() = default; + + virtual ~Control() = default; + + public: + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + }; + + /** \brief Definition of a compound control */ + class CompoundControl : public Control + { + public: + CompoundControl() = default; + + ~CompoundControl() override = default; + + /** \brief Cast a component of this instance to a desired type. */ + template + const T *as(unsigned int index) const + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(components[index]); + } + + /** \brief Cast a component of this instance to a desired type. */ + template + T *as(unsigned int index) + { + /** \brief Make sure the type we are allocating is indeed a state */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(components[index]); + } + + /** \brief Return the i-th control component */ + Control *operator[](unsigned int index) + { + return components[index]; + } + + /** \brief The components that make up a compound control */ + Control **components; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSampler.h new file mode 100644 index 00000000..93ee0d12 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSampler.h @@ -0,0 +1,163 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_CONTROL_SAMPLER_ +#define OMPL_CONTROL_CONTROL_SAMPLER_ + +#include "ompl/base/State.h" +#include "ompl/control/Control.h" +#include "ompl/util/RandomNumbers.h" +#include "ompl/util/ClassForward.h" +#include +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(ControlSpace); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::ControlSampler */ + OMPL_CLASS_FORWARD(ControlSampler); + /// @endcond + + /** \class ompl::control::ControlSamplerPtr + \brief A shared pointer wrapper for ompl::control::ControlSampler */ + + /** \brief Abstract definition of a control sampler. Motion + planners that need to sample controls will call functions + from this class. Planners should call the versions of + sample() and sampleNext() with most arguments, whenever + this information is available. */ + class ControlSampler + { + public: + // non-copyable + ControlSampler(const ControlSampler &) = delete; + ControlSampler &operator=(const ControlSampler &) = delete; + + /** \brief Constructor takes the state space to construct samples for as argument */ + ControlSampler(const ControlSpace *space) : space_(space) + { + } + + virtual ~ControlSampler() = default; + + /** \brief Sample a control. All other control sampling + functions default to this one, unless a user-specified + implementation is given. */ + virtual void sample(Control *control) = 0; + + /** \brief Sample a control, given it is applied to a + specific state (\e state). The default implementation calls the + previous definition of sample(). Providing a different + implementation of this function is useful if, for + example, the sampling of controls depends on the state + of the system. When attempting to sample controls that + keep a system stable, for example, knowing the state + at which the control is applied is important. */ + virtual void sample(Control *control, const base::State *state); + + /** \brief Sample a control, given the previously applied + control. The default implementation calls the first + definition of sample(). For some systems it is + possible that large changes in controls are not + desirable. For example, switching from maximum + acceleration to maximum deceleration is not desirable + when driving a car. */ + virtual void sampleNext(Control *control, const Control *previous); + + /** \brief Sample a control, given the previously applied + control and that it is applied to a specific + state. The default implementation calls the first + definition of sample(), even if other implementations + of the sampleNext() shown above are provided. Often + this function needs to be overridden as it is the + function planners typically call. */ + virtual void sampleNext(Control *control, const Control *previous, const base::State *state); + + /** \brief Sample a number of steps to execute a control for */ + virtual unsigned int sampleStepCount(unsigned int minSteps, unsigned int maxSteps); + + protected: + /** \brief The control space this sampler operates on */ + const ControlSpace *space_; + + /** \brief Instance of random number generator */ + RNG rng_; + }; + + /** \brief Definition of a compound control sampler. This is useful to construct samplers for compound controls. + */ + class CompoundControlSampler : public ControlSampler + { + public: + /** \brief Constructor */ + CompoundControlSampler(const ControlSpace *space) : ControlSampler(space) + { + } + + /** \brief Destructor. This frees the added samplers as well. */ + ~CompoundControlSampler() override = default; + + /** \brief Add a sampler as part of the new compound + sampler. This sampler is used to sample part of the + compound control. */ + virtual void addSampler(const ControlSamplerPtr &sampler); + + void sample(Control *control) override; + void sample(Control *control, const base::State *state) override; + void sampleNext(Control *control, const Control *previous) override; + void sampleNext(Control *control, const Control *previous, const base::State *state) override; + + protected: + /** \brief The instances of samplers used for compound sampler */ + std::vector samplers_; + + private: + /** \brief Number of sampler instances */ + unsigned int samplerCount_; + }; + + /** \brief Definition of a function that can allocate a control sampler */ + using ControlSamplerAllocator = std::function; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpace.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpace.h new file mode 100644 index 00000000..594453bc --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpace.h @@ -0,0 +1,290 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_CONTROL_SPACE_ +#define OMPL_CONTROL_CONTROL_SPACE_ + +#include "ompl/base/StateSpace.h" +#include "ompl/control/Control.h" +#include "ompl/control/ControlSampler.h" +#include "ompl/control/ControlSpaceTypes.h" +#include "ompl/util/Console.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::ControlSpace */ + OMPL_CLASS_FORWARD(ControlSpace); + /// @endcond + + /** \class ompl::control::ControlSpacePtr + \brief A shared pointer wrapper for ompl::control::ControlSpace */ + + /** \brief A control space representing the space of applicable controls */ + class ControlSpace + { + public: + /** \brief Define the type of control allocated by this control space */ + using ControlType = ompl::control::Control; + + // non-copyable + ControlSpace(const ControlSpace &) = delete; + ControlSpace &operator=(const ControlSpace &) = delete; + + /** \brief Construct a control space, given the state space */ + ControlSpace(base::StateSpacePtr stateSpace); + + virtual ~ControlSpace(); + + /** \brief Cast this instance to a desired type. */ + template + T *as() + { + /** \brief Make sure the type we are casting to is indeed a control space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Cast this instance to a desired type. */ + template + const T *as() const + { + /** \brief Make sure the type we are casting to is indeed a control space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(this); + } + + /** \brief Get the name of the control space */ + const std::string &getName() const; + + /** \brief Set the name of the control space */ + void setName(const std::string &name); + + /** \brief Get the type of the control space. The type can be + used to verify whether two space instances are of + the same type */ + int getType() const + { + return type_; + } + + /** \brief Return the state space this control space depends on */ + const base::StateSpacePtr &getStateSpace() const + { + return stateSpace_; + } + + /** \brief Get the dimension of this control space */ + virtual unsigned int getDimension() const = 0; + + /** \brief Allocate memory for a control */ + virtual Control *allocControl() const = 0; + + /** \brief Free the memory of a control */ + virtual void freeControl(Control *control) const = 0; + + /** \brief Copy a control to another */ + virtual void copyControl(Control *destination, const Control *source) const = 0; + + /** \brief Check if two controls are the same */ + virtual bool equalControls(const Control *control1, const Control *control2) const = 0; + + /** \brief Make the control have no effect if it were to be applied to a state for any amount of time. */ + virtual void nullControl(Control *control) const = 0; + + /** \brief Allocate the default control sampler */ + virtual ControlSamplerPtr allocDefaultControlSampler() const = 0; + + /** \brief Allocate an instance of the control sampler for this space. This sampler will be allocated with + the + sampler allocator that was previously specified by setControlSamplerAllocator() or, if no sampler + allocator was specified, + allocDefaultControlSampler() is called */ + virtual ControlSamplerPtr allocControlSampler() const; + + /** \brief Set the sampler allocator to use */ + void setControlSamplerAllocator(const ControlSamplerAllocator &csa); + + /** \brief Clear the control sampler allocator (reset to default) */ + void clearControlSamplerAllocator(); + + /** \brief Many controls contain a number of double values. This function provides a means to get the + memory address of a double value from a control \e control located at position \e index. The first + double value + is returned for \e index = 0. If \e index is too large (does not point to any double values in the + control), + the return value is nullptr. */ + virtual double *getValueAddressAtIndex(Control *control, unsigned int index) const; + + /** \brief Print a control to a stream */ + virtual void printControl(const Control *control, std::ostream &out) const; + + /** \brief Print the settings for this control space to a stream */ + virtual void printSettings(std::ostream &out) const; + + /** \brief Perform final setup steps. This function is automatically called by the SpaceInformation */ + virtual void setup(); + + /** \brief Returns the serialization size for a single control in this space */ + virtual unsigned int getSerializationLength() const; + + /** \brief Serializes the given control into the serialization buffer. */ + virtual void serialize(void *serialization, const Control *ctrl) const; + + /** \brief Deserializes a control from the serialization buffer. */ + virtual void deserialize(Control *ctrl, const void *serialization) const; + + /** \brief Compute an array of ints that uniquely identifies the structure of the control space. + The first element of the signature is the number of integers that follow */ + void computeSignature(std::vector &signature) const; + + /** \brief Check if the control space is compound */ + virtual bool isCompound() const; + + protected: + /** \brief A type assigned for this control space */ + int type_; + + /** \brief The state space controls can be applied to */ + base::StateSpacePtr stateSpace_; + + /** \brief An optional control sampler allocator */ + ControlSamplerAllocator csa_; + + private: + /** \brief The name of this control space */ + std::string name_; + }; + + /** \brief A control space to allow the composition of control spaces */ + class CompoundControlSpace : public ControlSpace + { + public: + /** \brief Define the type of control allocated by this control space */ + using ControlType = ompl::control::CompoundControl; + + /** \brief Constructor. The corresponding state space needs to be specified. */ + CompoundControlSpace(const base::StateSpacePtr &stateSpace) + : ControlSpace(stateSpace), componentCount_(0), locked_(false) + { + } + + ~CompoundControlSpace() override = default; + + /** \brief Cast a component of this instance to a desired type. */ + template + T *as(const unsigned int index) const + { + /** \brief Make sure the type we are casting to is indeed a control space */ + BOOST_CONCEPT_ASSERT((boost::Convertible)); + + return static_cast(getSubspace(index).get()); + } + + /** \brief Adds a control space as a component of the compound control space. */ + virtual void addSubspace(const ControlSpacePtr &component); + + /** \brief Get the number of control spaces that make up the compound control space */ + unsigned int getSubspaceCount() const; + + /** \brief Get a specific subspace from the compound control space */ + const ControlSpacePtr &getSubspace(unsigned int index) const; + + /** \brief Get a specific subspace from the compound control space */ + const ControlSpacePtr &getSubspace(const std::string &name) const; + + unsigned int getDimension() const override; + + Control *allocControl() const override; + + void freeControl(Control *control) const override; + + void copyControl(Control *destination, const Control *source) const override; + + bool equalControls(const Control *control1, const Control *control2) const override; + + void nullControl(Control *control) const override; + + ControlSamplerPtr allocDefaultControlSampler() const override; + + double *getValueAddressAtIndex(Control *control, unsigned int index) const override; + + void printControl(const Control *control, std::ostream &out = std::cout) const override; + + void printSettings(std::ostream &out) const override; + + void setup() override; + + /** \brief Returns the serialization size for a single control in this space */ + unsigned int getSerializationLength() const override; + + /** \brief Serializes the given control into the serialization buffer. */ + void serialize(void *serialization, const Control *ctrl) const override; + + /** \brief Deserializes a control from the serialization buffer. */ + void deserialize(Control *ctrl, const void *serialization) const override; + + bool isCompound() const override; + + /** \brief Lock this control space. This means no further + control spaces can be added as components. This function can + be for instance called from the constructor of a state space + that inherits from CompoundControlSpace to prevent the + user to add further components. */ + void lock(); + + protected: + /** \brief The component control spaces that make up the compound control space */ + std::vector components_; + + /** \brief The number of contained components */ + unsigned int componentCount_; + + /** \brief Flag indicating whether adding further components is allowed or not */ + bool locked_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpaceTypes.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpaceTypes.h new file mode 100644 index 00000000..52e5f987 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpaceTypes.h @@ -0,0 +1,64 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_CONTROL_SPACE_TYPES_ +#define OMPL_CONTROL_CONTROL_SPACE_TYPES_ + +namespace ompl +{ + namespace control + { + /** \brief The type of a control space */ + enum ControlSpaceType + { + + /** \brief Unset type; this is the default type */ + CONTROL_SPACE_UNKNOWN = 0, + + /** \brief ompl::control::RealVectorControlSpace */ + CONTROL_SPACE_REAL_VECTOR = 1, + + /** \brief ompl::control::DiscreteControlSpace */ + CONTROL_SPACE_DISCRETE = 2, + + /** \brief Number of control space types; To add new types, + use values that are larger than the count */ + CONTROL_SPACE_TYPE_COUNT + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/DirectedControlSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/DirectedControlSampler.h new file mode 100644 index 00000000..b46c25dc --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/DirectedControlSampler.h @@ -0,0 +1,107 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_DIRECTED_CONTROL_SAMPLER_ +#define OMPL_CONTROL_DIRECTED_CONTROL_SAMPLER_ + +#include "ompl/base/State.h" +#include "ompl/control/Control.h" +#include "ompl/util/ClassForward.h" +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + OMPL_CLASS_FORWARD(DirectedControlSampler); + /// @endcond + + /** \class ompl::control::DirectedControlSamplerPtr + \brief A shared pointer wrapper for ompl::control::DirectedControlSampler */ + + /** \brief Abstract definition of a directed control sampler. Motion + planners that need to sample controls that take the system to a desired direction will call functions + from this class. Planners should call the versions of sampleTo() with most arguments, whenever this + information is available. + If no direction information is available, the use of a ControlSampler is perhaps more appropriate. */ + class DirectedControlSampler + { + public: + // non-copyable + DirectedControlSampler(const DirectedControlSampler &) = delete; + DirectedControlSampler &operator=(const DirectedControlSampler &) = delete; + + /** \brief Constructor takes the state space to construct samples for as argument */ + DirectedControlSampler(const SpaceInformation *si) : si_(si) + { + } + + virtual ~DirectedControlSampler() = default; + + /** \brief Sample a control given that it will be applied to state + \e state and the intention is to reach state \e target. This is + useful for some algorithms that have a notion of direction in + their exploration (e.g., \ref cRRT). Furthermore, return the + duration for which this control should be applied. The state + \e dest is modified to match the state reached with the computed + control and duration. The motion is checked for validity. */ + virtual unsigned int sampleTo(Control *control, const base::State *source, base::State *dest) = 0; + + /** \brief Sample a control given that it will be applied to state + \e state and the intention is to reach state \e dest. Also take + into account the fact that the previously applied control is \e + previous. This is useful for some algorithms that have a notion + of direction in their exploration (e.g., \ref cRRT). + Furthermore, return the duration for which this control should + be applied. The state \e dest is modified to match the state + reached with the computed control and duration. The motion is + checked for validity. */ + virtual unsigned int sampleTo(Control *control, const Control *previous, const base::State *source, + base::State *dest) = 0; + + protected: + /** \brief The space information this sampler operates on */ + const SpaceInformation *si_; + }; + + /** \brief Definition of a function that can allocate a directed control sampler */ + using DirectedControlSamplerAllocator = std::function; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ODESolver.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ODESolver.h new file mode 100644 index 00000000..49c5972d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ODESolver.h @@ -0,0 +1,328 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_CONTROL_ODESOLVER_ +#define OMPL_CONTROL_ODESOLVER_ + +#include "ompl/control/Control.h" +#include "ompl/control/SpaceInformation.h" +#include "ompl/control/StatePropagator.h" +#include "ompl/util/Console.h" +#include "ompl/util/ClassForward.h" + +#include +#include +#include +#include +#include +#include +namespace odeint = boost::numeric::odeint; +#include +#include +#include +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(ODESolver); + /// @endcond + + /// \class ompl::control::ODESolverPtr + /// \brief A shared pointer wrapper for ompl::control::ODESolver + + /// \brief Abstract base class for an object that can solve ordinary differential + /// equations (ODE) of the type q' = f(q,u) using numerical integration. Classes + /// deriving from this must implement the solve method. The user must supply + /// the ODE to solve. + class ODESolver + { + public: + /// \brief Portable data type for the state values + using StateType = std::vector; + + /// \brief Callback function that defines the ODE. Accepts + /// the current state, input control, and output state. + using ODE = std::function; + + /// \brief Callback function to perform an event at the end of numerical + /// integration. This functionality is optional. + using PostPropagationEvent = + std::function; + + /// \brief Parameterized constructor. Takes a reference to SpaceInformation, + /// an ODE to solve, and the integration step size. + ODESolver(SpaceInformationPtr si, ODE ode, double intStep) + : si_(std::move(si)), ode_(std::move(ode)), intStep_(intStep) + { + } + + /// \brief Destructor. + virtual ~ODESolver() = default; + + /// \brief Set the ODE to solve + void setODE(const ODE &ode) + { + ode_ = ode; + } + + /// \brief Return the size of a single numerical integration step + double getIntegrationStepSize() const + { + return intStep_; + } + + /// \brief Set the size of a single numerical integration step + void setIntegrationStepSize(double intStep) + { + intStep_ = intStep; + } + + /** \brief Get the current instance of the space information */ + const SpaceInformationPtr &getSpaceInformation() const + { + return si_; + } + + /// \brief Retrieve a StatePropagator object that solves a system of ordinary + /// differential equations defined by an ODESolver. + /// An optional PostPropagationEvent can also be specified as a callback after + /// numerical integration is finished for further operations on the resulting + /// state. + static StatePropagatorPtr getStatePropagator(ODESolverPtr solver, + const PostPropagationEvent &postEvent = nullptr) + { + class ODESolverStatePropagator : public StatePropagator + { + public: + ODESolverStatePropagator(const ODESolverPtr &solver, PostPropagationEvent pe) + : StatePropagator(solver->si_), solver_(solver), postEvent_(std::move(pe)) + { + if (solver == nullptr) + OMPL_ERROR("ODESolverPtr does not reference a valid ODESolver object"); + } + + void propagate(const base::State *state, const Control *control, double duration, + base::State *result) const override + { + ODESolver::StateType reals; + si_->getStateSpace()->copyToReals(reals, state); + solver_->solve(reals, control, duration); + si_->getStateSpace()->copyFromReals(result, reals); + + if (postEvent_) + postEvent_(state, control, duration, result); + } + + protected: + ODESolverPtr solver_; + ODESolver::PostPropagationEvent postEvent_; + }; + return std::make_shared(std::move(solver), postEvent); + } + + protected: + /// \brief Solve the ODE given the initial state, and a control to apply for some duration. + virtual void solve(StateType &state, const Control *control, double duration) const = 0; + + /// \brief The SpaceInformation that this ODESolver operates in. + const SpaceInformationPtr si_; + + /// \brief Definition of the ODE to find solutions for. + ODE ode_; + + /// \brief The size of the numerical integration step. Should be small to minimize error. + double intStep_; + + /// @cond IGNORE + // Functor used by the boost::numeric::odeint stepper object + struct ODEFunctor + { + ODEFunctor(ODE o, const Control *ctrl) : ode(std::move(o)), control(ctrl) + { + } + + // boost::numeric::odeint will callback to this method during integration to evaluate the system + void operator()(const StateType ¤t, StateType &output, double /*time*/) + { + ode(current, control, output); + } + + ODE ode; + const Control *control; + }; + /// @endcond + }; + + /// \brief Basic solver for ordinary differential equations of the type q' = f(q, u), + /// where q is the current state of the system and u is a control applied to the + /// system. StateType defines the container object describing the state of the system. + /// Solver is the numerical integration method used to solve the equations. The default + /// is a fourth order Runge-Kutta method. This class wraps around the simple stepper + /// concept from boost::numeric::odeint. + template > + class ODEBasicSolver : public ODESolver + { + public: + /// \brief Parameterized constructor. Takes a reference to the SpaceInformation, + /// an ODE to solve, and an optional integration step size - default is 0.01 + ODEBasicSolver(const SpaceInformationPtr &si, const ODESolver::ODE &ode, double intStep = 1e-2) + : ODESolver(si, ode, intStep) + { + } + + protected: + /// \brief Solve the ODE using boost::numeric::odeint. + void solve(StateType &state, const Control *control, double duration) const override + { + Solver solver; + ODESolver::ODEFunctor odefunc(ode_, control); + odeint::integrate_const(solver, odefunc, state, 0.0, duration, intStep_); + } + }; + + /// \brief Solver for ordinary differential equations of the type q' = f(q, u), + /// where q is the current state of the system and u is a control applied to the + /// system. StateType defines the container object describing the state of the system. + /// Solver is the numerical integration method used to solve the equations. The default + /// is a fifth order Runge-Kutta Cash-Karp method with a fourth order error bound. + /// This class wraps around the error stepper concept from boost::numeric::odeint. + template > + class ODEErrorSolver : public ODESolver + { + public: + /// \brief Parameterized constructor. Takes a reference to the SpaceInformation, + /// an ODE to solve, and the integration step size - default is 0.01 + ODEErrorSolver(const SpaceInformationPtr &si, const ODESolver::ODE &ode, double intStep = 1e-2) + : ODESolver(si, ode, intStep) + { + } + + /// \brief Retrieves the error values from the most recent integration + ODESolver::StateType getError() + { + return error_; + } + + protected: + /// \brief Solve the ODE using boost::numeric::odeint. Save the resulting error values into error_. + void solve(StateType &state, const Control *control, double duration) const override + { + ODESolver::ODEFunctor odefunc(ode_, control); + + if (error_.size() != state.size()) + error_.assign(state.size(), 0.0); + + Solver solver; + solver.adjust_size(state); + + double time = 0.0; + while (time < duration + std::numeric_limits::epsilon()) + { + solver.do_step(odefunc, state, time, intStep_, error_); + time += intStep_; + } + } + + /// \brief The error values calculated during numerical integration + mutable ODESolver::StateType error_; + }; + + /// \brief Adaptive step size solver for ordinary differential equations of the type + /// q' = f(q, u), where q is the current state of the system and u is a control applied + /// to the system. The maximum integration error is bounded in this approach. + /// Solver is the numerical integration method used to solve the equations, and must implement + /// the error stepper concept from boost::numeric::odeint. The default + /// is a fifth order Runge-Kutta Cash-Karp method with a fourth order error bound. + template > + class ODEAdaptiveSolver : public ODESolver + { + public: + /// \brief Parameterized constructor. Takes a reference to the SpaceInformation, + /// an ODE to solve, and an optional integration step size - default is 0.01 + ODEAdaptiveSolver(const SpaceInformationPtr &si, const ODESolver::ODE &ode, double intStep = 1e-2) + : ODESolver(si, ode, intStep), maxError_(1e-6), maxEpsilonError_(1e-7) + { + } + + /// \brief Retrieve the total error allowed during numerical integration + double getMaximumError() const + { + return maxError_; + } + + /// \brief Set the total error allowed during numerical integration + void setMaximumError(double error) + { + maxError_ = error; + } + + /// \brief Retrieve the error tolerance during one step of numerical integration (local truncation error) + double getMaximumEpsilonError() const + { + return maxEpsilonError_; + } + + /// \brief Set the error tolerance during one step of numerical integration (local truncation error) + void setMaximumEpsilonError(double error) + { + maxEpsilonError_ = error; + } + + protected: + /// \brief Solve the ordinary differential equation given the input state + /// of the system, a control to apply to the system, and the duration to + /// apply the control. The value of \e state will contain the final + /// values for the system after integration. + void solve(StateType &state, const Control *control, double duration) const override + { + ODESolver::ODEFunctor odefunc(ode_, control); + auto solver = make_controlled(1.0e-6, 1.0e-6, Solver()); + odeint::integrate_adaptive(solver, odefunc, state, 0.0, duration, intStep_); + } + + /// \brief The maximum error allowed when performing numerical integration + double maxError_; + + /// \brief The maximum error allowed during one step of numerical integration + double maxEpsilonError_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PathControl.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PathControl.h new file mode 100644 index 00000000..3f3a8c39 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PathControl.h @@ -0,0 +1,223 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_PATH_CONTROL_ +#define OMPL_CONTROL_PATH_CONTROL_ + +#include "ompl/control/SpaceInformation.h" +#include "ompl/base/Path.h" +#include "ompl/geometric/PathGeometric.h" +#include + +namespace ompl +{ + namespace base + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(OptimizationObjective); + /// @endcond + } // namespace base + + namespace control + { + /** \brief Definition of a control path. + + This is the type of path produced when planning with + differential constraints. */ + class PathControl : public base::Path + { + public: + /** \brief Constructor */ + PathControl(const base::SpaceInformationPtr &si); + + /** \brief Copy constructor */ + PathControl(const PathControl &path); + + ~PathControl() override + { + freeMemory(); + } + + /** \brief Assignment operator */ + PathControl &operator=(const PathControl &other); + + /** \brief Not yet implemented. */ + base::Cost cost(const base::OptimizationObjectivePtr &opt) const override; + + /** \brief The path length (sum of control durations) */ + double length() const override; + + /** \brief Check if the path is valid */ + bool check() const override; + + /** \brief Print the path to a stream */ + void print(std::ostream &out) const override; + /** \brief Print the path as a real-valued matrix where the + i-th row represents the i-th state along the path, followed + by the control and duration needed to reach this state. For + the first state the control and duration are zeroes. The + state components printed are those returned by + ompl::base::StateSpace::copyToReals, while the control + components printed are the discrete components (if any) + followed by the real-valued ones as returned by + ompl::control::ControlSpace::getValueAddressAtIndex. */ + virtual void printAsMatrix(std::ostream &out) const; + + /** \brief Convert this path into a geometric path (interpolation is performed and then states are copied) + */ + geometric::PathGeometric asGeometric() const; + + /** @name Path operations + @{ */ + + /** \brief Append \e state to the end of the path; it is assumed \e state is the first state, so no control + is applied. + The memory for \e state is copied. There are no checks to make sure the number of controls and states + make sense. */ + void append(const base::State *state); + + /** \brief Append \e state to the end of the path and assume \e control is applied for the duration \e + duration. + The memory for \e state and for \e control is copied. There are no checks to make sure the number of + controls and states make sense. */ + void append(const base::State *state, const Control *control, double duration); + + /** \brief Make the path such that all controls are applied for a single time step (computes intermediate + * states) */ + void interpolate(); + + /** \brief Set this path to a random segment */ + void random(); + + /** \brief Set this path to a random valid segment. Sample \e attempts times for valid segments. Returns + * true on success.*/ + bool randomValid(unsigned int attempts); + + /** @} */ + + /** @name Functionality for accessing states and controls + @{ */ + + /** \brief Get the states that make up the path (as a reference, so it can be modified, hence the function + * is not const) */ + std::vector &getStates() + { + return states_; + } + + /** \brief Get the controls that make up the path (as a reference, so it can be modified, hence the function + * is not const) */ + std::vector &getControls() + { + return controls_; + } + + /** \brief Get the control durations used along the path (as a reference, so it can be modified, hence the + * function is not const) */ + std::vector &getControlDurations() + { + return controlDurations_; + } + + /** \brief Get the state located at \e index along the path */ + base::State *getState(unsigned int index) + { + return states_[index]; + } + + /** \brief Get the state located at \e index along the path */ + const base::State *getState(unsigned int index) const + { + return states_[index]; + } + + /** \brief Get the control located at \e index along the path. This is the control that gets applied to the + * state located at \e index */ + Control *getControl(unsigned int index) + { + return controls_[index]; + } + + /** \brief Get the control located at \e index along the path. This is the control that gets applied to the + * state located at \e index */ + const Control *getControl(unsigned int index) const + { + return controls_[index]; + } + + /** \brief Get the duration of the control at \e index, which gets applied to the state at \e index. */ + double getControlDuration(unsigned int index) const + { + return controlDurations_[index]; + } + + /** \brief Get the number of states (way-points) that make up this path */ + std::size_t getStateCount() const + { + return states_.size(); + } + + /** \brief Get the number of controls applied along this path. This should be equal to getStateCount() - 1 + * unless there are 0 states, in which case the number of controls will also be 0. */ + std::size_t getControlCount() const + { + return controls_.size(); + } + + /** @} */ + + protected: + /** \brief The list of states that make up the path */ + std::vector states_; + + /** \brief The control applied at each state. This array contains one element less than the list of states + */ + std::vector controls_; + + /** \brief The duration of the control applied at each state. This array contains one element less than the + * list of states */ + std::vector controlDurations_; + + /** \brief Free the memory allocated by the path */ + void freeMemory(); + + /** \brief Copy the content of a path to this one */ + void copyFrom(const PathControl &other); + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerData.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerData.h new file mode 100644 index 00000000..b22e9801 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerData.h @@ -0,0 +1,174 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll */ + +#ifndef OMPL_CONTROL_PLANNER_DATA_ +#define OMPL_CONTROL_PLANNER_DATA_ + +#include "ompl/base/PlannerData.h" +#include "ompl/control/SpaceInformation.h" +#include "ompl/control/Control.h" +#include + +namespace ompl +{ + namespace control + { + /// \brief Representation of an edge in PlannerData for planning with controls. + /// This structure encodes a specific control and a duration to apply the control. + /// \remarks If using PlannerDataEdgeControl in conjunction with PlannerDataStorage, + /// (i.e., storing the PlannerData from a controls planner) you must export a GUID + /// for PlannerDataEdgeControl so that the serializer can identify the derived + /// edge class: + /// \code + /// #include + /// ... + /// BOOST_CLASS_EXPORT(ompl::control::PlannerDataEdgeControl); + /// \endcode + class PlannerDataEdgeControl : public base::PlannerDataEdge + { + public: + /// \brief Constructor. Accepts a control pointer and a duration. + PlannerDataEdgeControl(const Control *c, double duration) : c_(c), duration_(duration) + { + } + /// \brief Copy constructor. + PlannerDataEdgeControl(const PlannerDataEdgeControl &rhs) : c_(rhs.c_), duration_(rhs.duration_) + { + } + + ~PlannerDataEdgeControl() override = default; + + base::PlannerDataEdge *clone() const override + { + return static_cast(new PlannerDataEdgeControl(*this)); + } + + /// \brief Return the control associated with this edge. + const Control *getControl() const + { + return c_; + } + /// \brief Return the duration associated with this edge. + double getDuration() const + { + return duration_; + } + + bool operator==(const PlannerDataEdge &rhs) const override + { + const auto *rhsc = static_cast(&rhs); + if (c_ == rhsc->c_) + return static_cast(*this) == rhs; + return false; + } + + protected: + friend class boost::serialization::access; + friend class PlannerDataStorage; + friend class PlannerData; + + PlannerDataEdgeControl() = default; + + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar &boost::serialization::base_object(*this); + ar & duration_; + // Serializing the control is handled by control::PlannerDataStorage + } + + const Control *c_{nullptr}; + double duration_; + }; + + /// \copydoc ompl::base::PlannerData + /// \brief This class assumes edges are derived from PlannerDataEdgeControl. + /// If this is not the case, see base::PlannerData. + class PlannerData : public base::PlannerData + { + public: + /// \brief Constructor. Accepts a SpaceInformationPtr for the space planned in. + PlannerData(const SpaceInformationPtr &siC); + /// \brief Destructor. + ~PlannerData() override; + + /// \brief Removes the vertex associated with the given data. If the + /// vertex does not exist, false is returned. + /// This method has O(n) complexity in the number of vertices. + bool removeVertex(const base::PlannerDataVertex &st) override; + /// \brief Removes the vertex with the given index. If the index is + /// out of range, false is returned. + /// This method has O(n) complexity in the number of vertices. + bool removeVertex(unsigned int vIndex) override; + + /// \brief Removes the edge between vertex indexes \e v1 and \e v2. Success is returned. + bool removeEdge(unsigned int v1, unsigned int v2) override; + /// \brief Removes the edge between the vertices associated with the given vertex data. + /// Success is returned. + bool removeEdge(const base::PlannerDataVertex &v1, const base::PlannerDataVertex &v2) override; + + /// \brief Clears the entire data structure + void clear() override; + + /// \brief Creates a deep copy of the states contained in the vertices of this + /// PlannerData structure so that when the planner that created this instance goes + /// out of scope, all data remains intact. + /// \remarks Shallow state pointers inside of the PlannerDataVertex objects already + /// in this PlannerData will be replaced with clones which are scoped to this PlannerData + /// object. A subsequent call to this method is necessary after any other vertices are + /// added to ensure that this PlannerData instance is fully decoupled. + void decoupleFromPlanner() override; + + /// \brief Return the instance of SpaceInformation used in this PlannerData + const SpaceInformationPtr &getSpaceInformation() const; + + /// \brief Returns true if this PlannerData instance has controls associated with it + bool hasControls() const override; + + protected: + /// \brief The instance of control::SpaceInformation associated with this data + SpaceInformationPtr siC_; + /// \brief A list of controls that are allocated during the decoupleFromPlanner method. + /// These controls are freed by PlannerData in the destructor. + std::set decoupledControls_; + + private: + void freeMemory(); + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerDataStorage.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerDataStorage.h new file mode 100644 index 00000000..6d9daccf --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerDataStorage.h @@ -0,0 +1,191 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_CONTROL_PLANNER_DATA_STORAGE_ +#define OMPL_CONTROL_PLANNER_DATA_STORAGE_ + +#include "ompl/base/PlannerDataStorage.h" +#include "ompl/control/PlannerData.h" +#include "ompl/control/SpaceInformation.h" + +namespace ompl +{ + namespace control + { + /// \copydoc ompl::base::PlannerDataStorage + /// \brief It is assumed that the edges in stored/loaded PlannerData can + /// be cast to PlannerDataEdgeControl in this class. If this is not the + /// case, see ompl::base::PlannerDataStorage. + class PlannerDataStorage : public base::PlannerDataStorage + { + public: + /// \brief Default constructor + PlannerDataStorage() = default; + /// \brief Destructor + ~PlannerDataStorage() override = default; + + /// \brief Load the PlannerData structure from the given filename. + bool load(const char *filename, base::PlannerData &pd) override; + + /// \brief Deserializes the structure from the given stream. + bool load(std::istream &in, base::PlannerData &pd) override; + + /// \brief Store (serialize) the structure to the given filename. + /// The StateSpace and ControlSpace that was used to store the data + /// must match those inside of the argument PlannerData. + bool store(const base::PlannerData &pd, const char *filename) override; + + /// \brief Load the PlannerData structure from the given stream. + /// The StateSpace and ControlSpace that was used to store the data + /// must match those inside of the argument PlannerData. + bool store(const base::PlannerData &pd, std::ostream &out) override; + + protected: + /// @cond IGNORE + // Information stored at the beginning of the PlannerData archive + struct Header : base::PlannerDataStorage::Header + { + /// \brief Signature of control space that allocated the saved states in the vertices (see + /// ompl::base::StateSpace::computeSignature()) */ + std::vector control_signature; + + /// \brief boost::serialization routine + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar &boost::serialization::base_object(*this); + ar & control_signature; + } + }; + + // The object containing all control edge data that will be stored + struct PlannerDataEdgeControlData : base::PlannerDataStorage::PlannerDataEdgeData + { + template + void serialize(Archive &ar, const unsigned int /*version*/) + { + ar &boost::serialization::base_object(*this); + ar & control_; + } + + std::vector control_; + }; + /// \endcond + + /// \brief Read \e numEdges from the binary input \e ia and store them as PlannerData. It is assumed + /// that the edges can be cast to ompl::control::PlannerDataEdgeControl. + void loadEdges(base::PlannerData &pd, unsigned int numEdges, boost::archive::binary_iarchive &ia) override + { + OMPL_DEBUG("Loading %d PlannerDataEdgeControl objects", numEdges); + + const ControlSpacePtr &space = + static_cast(pd).getSpaceInformation()->getControlSpace(); + std::vector controls; + + for (unsigned int i = 0; i < numEdges; ++i) + { + PlannerDataEdgeControlData edgeData; + ia >> edgeData; + + std::vector ctrlBuf(space->getSerializationLength()); + Control *ctrl = space->allocControl(); + controls.push_back(ctrl); + space->deserialize(ctrl, &edgeData.control_[0]); + const_cast(static_cast(edgeData.e_))->c_ = + ctrl; + + pd.addEdge(edgeData.endpoints_.first, edgeData.endpoints_.second, *edgeData.e_, + base::Cost(edgeData.weight_)); + + // We deserialized the edge object pointer, and we own it. + // Since addEdge copies the object, it is safe to free here. + delete edgeData.e_; + } + + // These edges are using control pointers allocated here. + // To avoid a memory leak, we decouple planner data from the + // 'planner', which will clone all controls and properly free the + // memory when PlannerData goes out of scope. Then it is safe + // to free all memory allocated here. + pd.decoupleFromPlanner(); + + for (auto &control : controls) + space->freeControl(control); + } + + /// \brief Serialize and store all edges in \e pd to the binary archive. It is assumed + /// that the edges can be cast to ompl::control::PlannerDataEdgeControl. + void storeEdges(const base::PlannerData &pd, boost::archive::binary_oarchive &oa) override + { + OMPL_DEBUG("Storing %d PlannerDataEdgeControl objects", pd.numEdges()); + + const ControlSpacePtr &space = + static_cast(pd).getSpaceInformation()->getControlSpace(); + std::vector ctrl(space->getSerializationLength()); + + std::vector edgeList; + for (unsigned int fromVertex = 0; fromVertex < pd.numVertices(); ++fromVertex) + { + edgeList.clear(); + pd.getEdges(fromVertex, edgeList); // returns the id of each edge + + // Process edges + for (unsigned int toVertex : edgeList) + { + // Get cost + base::Cost weight; + if (!pd.getEdgeWeight(fromVertex, toVertex, &weight)) + OMPL_ERROR("Unable to get edge weight"); + + // Convert to new structure + PlannerDataEdgeControlData edgeData; + edgeData.e_ = &pd.getEdge(fromVertex, toVertex); + edgeData.endpoints_.first = fromVertex; + edgeData.endpoints_.second = toVertex; + edgeData.weight_ = weight.value(); + space->serialize(&ctrl[0], + static_cast(edgeData.e_)->getControl()); + edgeData.control_ = ctrl; + oa << edgeData; + + } // for each edge + } // for each vertex + } + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleDirectedControlSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleDirectedControlSampler.h new file mode 100644 index 00000000..08718042 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleDirectedControlSampler.h @@ -0,0 +1,120 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Willow Garage nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_SIMPLE_DIRECTED_CONTROL_SAMPLER_ +#define OMPL_CONTROL_SIMPLE_DIRECTED_CONTROL_SAMPLER_ + +#include "ompl/control/DirectedControlSampler.h" +#include "ompl/control/ControlSampler.h" + +namespace ompl +{ + namespace control + { + /** \brief Implementation of a simple directed control + sampler. This is a basic implementation that does not + actually take direction into account and builds upon ControlSampler. + Instead, a set of k random controls are sampled, and the control that + gets the system closest to the target state is returned. + + @par External documentation + K-control sampling is first believed to be proposed in: + + S.M. LaValle and J.J. Kuffner, Randomized kinodynamic planning, Intl. J. of Robotics Research, vol. + 20, pp. 378–400, May 2001. DOI: [10.1177/02783640122067453](http://dx.doi.org/10.1177/02783640122067453)
+ [[PDF]](http://ijr.sagepub.com/content/20/5/378.full.pdf) + [[more]](http://msl.cs.uiuc.edu/~lavalle/rrtpubs.html) */ + class SimpleDirectedControlSampler : public DirectedControlSampler + { + public: + /** \brief Constructor takes the state space to construct samples for as argument + Optionally, a \e k value can be given to indicate the number of controls to + try when directing a system toward a specific state. Default value is 1. */ + SimpleDirectedControlSampler(const SpaceInformation *si, unsigned int k = 1); + + ~SimpleDirectedControlSampler() override; + + /** \brief Retrieve the number of controls to generate when finding the best control. */ + unsigned int getNumControlSamples() const + { + return numControlSamples_; + } + + /** \brief Set the number of controls to generate when finding the best control. */ + void setNumControlSamples(unsigned int numSamples) + { + numControlSamples_ = numSamples; + } + + /** \brief Sample a control given that it will be applied + to state \e state and the intention is to reach state + \e dest. This is useful for some algorithms that + have a notion of direction in their exploration (e.g., + \ref cRRT). Furthermore, return the duration for which + this control should be applied. The state + \e dest is modified to match the state reached with the computed + control and duration. The motion is checked for validity. */ + unsigned int sampleTo(Control *control, const base::State *source, base::State *dest) override; + + /** \brief Sample a control given that it will be applied + to state \e state and the intention is to reach state + \e dest. Also take into account the fact that the + previously applied control is \e previous. This is + useful for some algorithms that have a notion of + direction in their exploration (e.g., + \ref cRRT). Furthermore, return the duration for which + this control should be applied. The state \e dest is + modified to match the state reached with the computed + control and duration. The motion is checked for validity. */ + unsigned int sampleTo(Control *control, const Control *previous, const base::State *source, + base::State *dest) override; + + protected: + /** \brief Samples \e numControlSamples_ controls, and returns the + control that brings the system the closest to \e target */ + virtual unsigned int getBestControl(Control *control, const base::State *source, base::State *dest, + const Control *previous); + + /** \brief An instance of the control sampler*/ + ControlSamplerPtr cs_; + + /** \brief The number of controls to sample when finding the best control*/ + unsigned int numControlSamples_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleSetup.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleSetup.h new file mode 100644 index 00000000..9b6e1247 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleSetup.h @@ -0,0 +1,298 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_SIMPLE_SETUP_ +#define OMPL_CONTROL_SIMPLE_SETUP_ + +#include "ompl/base/Planner.h" +#include "ompl/control/SpaceInformation.h" +#include "ompl/control/PlannerData.h" +#include "ompl/base/ProblemDefinition.h" +#include "ompl/control/PathControl.h" +#include "ompl/geometric/PathGeometric.h" +#include "ompl/util/Console.h" +#include "ompl/util/Exception.h" + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SimpleSetup); + /// @endcond + + /** \class ompl::control::SimpleSetupPtr + \brief A shared pointer wrapper for ompl::control::SimpleSetup */ + + /** \brief Create the set of classes typically needed to solve a + control problem */ + class SimpleSetup + { + public: + /** \brief Constructor needs the control space used for planning. */ + explicit SimpleSetup(const SpaceInformationPtr &si); + + /** \brief Constructor needs the control space used for planning. */ + explicit SimpleSetup(const ControlSpacePtr &space); + + virtual ~SimpleSetup() = default; + + /** \brief Get the current instance of the space information */ + const SpaceInformationPtr &getSpaceInformation() const + { + return si_; + } + + /** \brief Get the current instance of the problem definition */ + const base::ProblemDefinitionPtr &getProblemDefinition() const + { + return pdef_; + } + + /** \brief Get the current instance of the problem definition */ + base::ProblemDefinitionPtr &getProblemDefinition() + { + return pdef_; + } + + /** \brief Get the current instance of the state space */ + const base::StateSpacePtr &getStateSpace() const + { + return si_->getStateSpace(); + } + + /** \brief Get the current instance of the control space */ + const ControlSpacePtr &getControlSpace() const + { + return si_->getControlSpace(); + } + + /** \brief Get the current instance of the state validity checker */ + const base::StateValidityCheckerPtr &getStateValidityChecker() const + { + return si_->getStateValidityChecker(); + } + + /** \brief Get the instance of the state propagator being used */ + const StatePropagatorPtr &getStatePropagator() const + { + return si_->getStatePropagator(); + } + + /** \brief Get the current goal definition */ + const base::GoalPtr &getGoal() const + { + return pdef_->getGoal(); + } + + /** \brief Get the current planner */ + const base::PlannerPtr &getPlanner() const + { + return planner_; + } + + /** \brief Get the planner allocator */ + const base::PlannerAllocator &getPlannerAllocator() const + { + return pa_; + } + + /** \brief Return true if a solution path is available (previous call to solve() was successful) and the + * solution is exact (not approximate) */ + bool haveExactSolutionPath() const; + + /** \brief Return true if a solution path is available (previous call to solve() was successful). The + * solution may be approximate. */ + bool haveSolutionPath() const + { + return pdef_->getSolutionPath() != nullptr; + } + + /** \brief Get the solution path. Throw an exception if no solution is available */ + PathControl &getSolutionPath() const; + + /** \brief Get information about the exploration data structure the motion planner used. */ + void getPlannerData(base::PlannerData &pd) const; + + /** \brief Set the state validity checker to use */ + void setStateValidityChecker(const base::StateValidityCheckerPtr &svc) + { + si_->setStateValidityChecker(svc); + } + + /** \brief Set the state validity checker to use */ + void setStateValidityChecker(const base::StateValidityCheckerFn &svc) + { + si_->setStateValidityChecker(svc); + } + + /** \brief Set the function that performs state propagation */ + void setStatePropagator(const StatePropagatorFn &sp) + { + si_->setStatePropagator(sp); + } + + /** \brief Set the instance of StatePropagator to perform state propagation */ + void setStatePropagator(const StatePropagatorPtr &sp) + { + si_->setStatePropagator(sp); + } + + /** \brief Set the optimization objective to use */ + void setOptimizationObjective(const base::OptimizationObjectivePtr &optimizationObjective) + { + pdef_->setOptimizationObjective(optimizationObjective); + } + + /** \brief Set the start and goal states to use. */ + void setStartAndGoalStates(const base::ScopedState<> &start, const base::ScopedState<> &goal, + const double threshold = std::numeric_limits::epsilon()) + { + pdef_->setStartAndGoalStates(start, goal, threshold); + } + + /** \brief A simple form of setGoal(). The goal will be an instance of ompl::base::GoalState */ + void setGoalState(const base::ScopedState<> &goal, + const double threshold = std::numeric_limits::epsilon()) + { + pdef_->setGoalState(goal, threshold); + } + + /** \brief Add a starting state for planning. This call is not + needed if setStartAndGoalStates() has been called. */ + void addStartState(const base::ScopedState<> &state) + { + pdef_->addStartState(state); + } + + /** \brief Clear the currently set starting states */ + void clearStartStates() + { + pdef_->clearStartStates(); + } + + /** \brief Clear the currently set starting states and add \e state as the starting state */ + void setStartState(const base::ScopedState<> &state) + { + clearStartStates(); + addStartState(state); + } + + /** \brief Set the goal for planning. This call is not + needed if setStartAndGoalStates() has been called. */ + void setGoal(const base::GoalPtr &goal) + { + pdef_->setGoal(goal); + } + + /** \brief Set the planner to use. If the planner is not + set, an attempt is made to use the planner + allocator. If no planner allocator is available + either, a default planner is set. */ + void setPlanner(const base::PlannerPtr &planner) + { + if (planner && planner->getSpaceInformation().get() != si_.get()) + throw Exception("Planner instance does not match space information"); + planner_ = planner; + configured_ = false; + } + + /** \brief Set the planner allocator to use. This is only + used if no planner has been set. This is optional -- a default + planner will be used if no planner is otherwise specified. */ + void setPlannerAllocator(const base::PlannerAllocator &pa) + { + pa_ = pa; + planner_.reset(); + configured_ = false; + } + + /** \brief Run the planner for a specified amount of time (default is 1 second) */ + virtual base::PlannerStatus solve(double time = 1.0); + + /** \brief Run the planner until \e ptc becomes true (at most) */ + virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc); + + /** \brief Return the status of the last planning attempt */ + base::PlannerStatus getLastPlannerStatus() const + { + return last_status_; + } + + /** \brief Get the amount of time (in seconds) spent during the last planning step */ + double getLastPlanComputationTime() const + { + return planTime_; + } + + /** \brief Clear all planning data. This only includes + data generated by motion plan computation. Planner + settings, start & goal states are not affected. */ + virtual void clear(); + + /** \brief Print information about the current setup */ + virtual void print(std::ostream &out = std::cout) const; + + /** \brief This method will create the necessary classes + for planning. The solve() method will call this + function automatically. */ + virtual void setup(); + + protected: + /// The created space information + SpaceInformationPtr si_; + + /// The created problem definition + base::ProblemDefinitionPtr pdef_; + + /// The maintained planner instance + base::PlannerPtr planner_; + + /// The optional planner allocator + base::PlannerAllocator pa_; + + /// Flag indicating whether the classes needed for planning are set up + bool configured_; + + /// The amount of time the last planning step took + double planTime_; + + /// The status of the last planning request + base::PlannerStatus last_status_; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SpaceInformation.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SpaceInformation.h new file mode 100644 index 00000000..85d42e7d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SpaceInformation.h @@ -0,0 +1,321 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_SPACE_INFORMATION_ +#define OMPL_CONTROL_SPACE_INFORMATION_ + +#include + +#include "ompl/base/SpaceInformation.h" +#include "ompl/control/ControlSpace.h" +#include "ompl/control/ControlSampler.h" +#include "ompl/control/DirectedControlSampler.h" +#include "ompl/control/StatePropagator.h" +#include "ompl/control/Control.h" +#include "ompl/util/ClassForward.h" + +namespace ompl +{ + /** \brief This namespace contains sampling based planning + routines used by planning under differential constraints */ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::SpaceInformation */ + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /** \class ompl::control::SpaceInformationPtr + \brief A shared pointer wrapper for ompl::control::SpaceInformation */ + + /** \brief A function that achieves state propagation.*/ + using StatePropagatorFn = + std::function; + + /** \brief Space information containing necessary information for planning with controls. setup() needs to be + * called before use. */ + class SpaceInformation : public base::SpaceInformation + { + public: + /** \brief Constructor. Sets the instance of the state and control spaces to plan with. */ + SpaceInformation(const base::StateSpacePtr &stateSpace, ControlSpacePtr controlSpace); + + ~SpaceInformation() override = default; + + /** \brief Get the control space */ + const ControlSpacePtr &getControlSpace() const + { + return controlSpace_; + } + + /** @name Control memory management + @{ */ + + /** \brief Allocate memory for a control */ + Control *allocControl() const + { + return controlSpace_->allocControl(); + } + + /** \brief Free the memory of a control */ + void freeControl(Control *control) const + { + controlSpace_->freeControl(control); + } + + /** \brief Copy a control to another */ + void copyControl(Control *destination, const Control *source) const + { + controlSpace_->copyControl(destination, source); + } + + /** \brief Clone a control */ + Control *cloneControl(const Control *source) const + { + Control *copy = controlSpace_->allocControl(); + controlSpace_->copyControl(copy, source); + return copy; + } + + /** @} */ + + /** @name Topology-specific control operations (as in the control space) + @{ */ + + /** \brief Print a control to a stream */ + void printControl(const Control *control, std::ostream &out = std::cout) const + { + controlSpace_->printControl(control, out); + } + + /** \brief Check if two controls are the same */ + bool equalControls(const Control *control1, const Control *control2) const + { + return controlSpace_->equalControls(control1, control2); + } + + /** \brief Make the control have no effect if it were to be applied to a state for any amount of time. */ + void nullControl(Control *control) const + { + controlSpace_->nullControl(control); + } + + /** @} */ + + /** @name Sampling of controls + @{ */ + + /** \brief Allocate a control sampler */ + ControlSamplerPtr allocControlSampler() const + { + return controlSpace_->allocControlSampler(); + } + + /** \brief Set the minimum and maximum number of steps a control is propagated for */ + void setMinMaxControlDuration(unsigned int minSteps, unsigned int maxSteps) + { + minSteps_ = minSteps; + maxSteps_ = maxSteps; + } + + /** \brief Set the minimum number of steps a control is propagated for */ + void setMinControlDuration(unsigned int minSteps) + { + minSteps_ = minSteps; + } + + /** \brief Set the minimum and maximum number of steps a control is propagated for */ + void setMaxControlDuration(unsigned int maxSteps) + { + maxSteps_ = maxSteps; + } + + /** \brief Get the minimum number of steps a control is propagated for */ + unsigned int getMinControlDuration() const + { + return minSteps_; + } + + /** \brief Get the maximum number of steps a control is propagated for */ + unsigned int getMaxControlDuration() const + { + return maxSteps_; + } + + /** \brief Allocate an instance of the DirectedControlSampler to use. This will be the default + (SimpleDirectedControlSampler) unless + setDirectedControlSamplerAllocator() was previously called. */ + DirectedControlSamplerPtr allocDirectedControlSampler() const; + + /** \brief Set the allocator to use for the DirectedControlSampler */ + void setDirectedControlSamplerAllocator(const DirectedControlSamplerAllocator &dcsa); + + /** \brief Reset the DirectedControlSampler to be the default one */ + void clearDirectedSamplerAllocator(); + + /** @} */ + + /** @name Configuration of the state propagator + @{ */ + + /** \brief Get the instance of StatePropagator that performs state propagation */ + const StatePropagatorPtr &getStatePropagator() const + { + return statePropagator_; + } + + /** \brief Set the function that performs state propagation */ + void setStatePropagator(const StatePropagatorFn &fn); + + /** \brief Set the instance of StatePropagator to perform state propagation */ + void setStatePropagator(const StatePropagatorPtr &sp); + + /** \brief When controls are applied to states, they are applied for a time duration that is an integer + multiple of the stepSize, within the bounds specified by setMinMaxControlDuration() */ + void setPropagationStepSize(double stepSize) + { + stepSize_ = stepSize; + } + + /** \brief Propagation is performed at integer multiples of a specified step size. This function returns the + * value of this step size. */ + double getPropagationStepSize() const + { + return stepSize_; + } + /** @} */ + + /** @name Primitives for propagating the model of the system + @{ */ + + /** \brief Propagate the model of the system forward, starting a a given state, with a given control, for a + given number of steps. + \param state the state to start at + \param control the control to apply + \param steps the number of time steps to apply the control for. Each time step is of length + getPropagationStepSize() + \param result the state at the end of the propagation */ + void propagate(const base::State *state, const Control *control, int steps, base::State *result) const; + + /** \brief Some systems can only propagate forward in time (i.e., the \e steps argument for the propagate() + function is always positive). If this is the case, this function will return false. Planners that need + backward propagation (negative \e steps) will call this function to check. If backward propagation is + possible, this function will return true (this is the default). */ + bool canPropagateBackward() const; + + /** \brief Propagate the model of the system forward, starting at a given state, with a given control, for a + given number of steps. + Stop if a collision is found and return the number of steps actually performed without collision. If no + collision is found, the returned value is + equal to the \e steps argument. If a collision is found after the first step, the return value is 0 and + \e result = \e state. + \param state the state to start at + \param control the control to apply + \param steps the maximum number of time steps to apply the control for. Each time step is of length + getPropagationStepSize(). If \e steps is negative, backward propagation will be performed. + \param result the state at the end of the propagation or the last valid state if a collision is found */ + unsigned int propagateWhileValid(const base::State *state, const Control *control, int steps, + base::State *result) const; + + /** \brief Propagate the model of the system forward, starting a a given state, with a given control, for a + given number of steps. + \param state the state to start at + \param control the control to apply + \param steps the number of time steps to apply the control for. Each time step is of length + getPropagationStepSize(). If \e steps is negative, backward propagation will be performed. + \param result the set of states along the propagated motion + \param alloc flag indicating whether memory for the states in \e result should be allocated + + \note Start state \e state is not included in \e result */ + void propagate(const base::State *state, const Control *control, int steps, + std::vector &result, bool alloc) const; + + /** \brief Propagate the model of the system forward, starting at a given state, with a given control, for a + given number of steps. + Stop if a collision is found and return the number of steps actually performed without collision. If no + collision is found, the returned value is + equal to the \e steps argument. If a collision is found after the first step, the return value is 0 and + no states are added to \e result. + If \e alloc is false and \e result cannot store all the generated states, propagation is stopped + prematurely (when \e result is full). + The starting state (\e state) is not included in \e result. The return value of the function indicates + how many states have been written to \e result. + + \param state the state to start at + \param control the control to apply + \param steps the maximum number of time steps to apply the control for. Each time step is of length + getPropagationStepSize(). If \e steps is negative, backward propagation will be performed. + \param result the set of states along the propagated motion (only valid states included) + \param alloc flag indicating whether memory for the states in \e result should be allocated + */ + unsigned int propagateWhileValid(const base::State *state, const Control *control, int steps, + std::vector &result, bool alloc) const; + + /** @} */ + + /** \brief Print information about the current instance of the state space */ + void printSettings(std::ostream &out = std::cout) const override; + + /** \brief Perform additional setup tasks (run once, before use) */ + void setup() override; + + protected: + /** Declare parameter settings */ + void declareParams(); + + /** \brief The control space describing the space of controls applicable to states in the state space */ + ControlSpacePtr controlSpace_; + + /** \brief The state propagator used to model the motion of the system being planned for */ + StatePropagatorPtr statePropagator_; + + /** \brief The minimum number of steps to apply a control for */ + unsigned int minSteps_{0}; + + /** \brief The maximum number of steps to apply a control for */ + unsigned int maxSteps_{0}; + + /** \brief Optional allocator for the DirectedControlSampler. If not specified, the default implementation + * is used */ + DirectedControlSamplerAllocator dcsa_; + + /** \brief The actual duration of each step */ + double stepSize_{0.}; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/StatePropagator.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/StatePropagator.h new file mode 100644 index 00000000..744fafc8 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/StatePropagator.h @@ -0,0 +1,129 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_STATE_PROPAGATOR_ +#define OMPL_CONTROL_STATE_PROPAGATOR_ + +#include "ompl/base/State.h" +#include "ompl/control/Control.h" +#include "ompl/util/ClassForward.h" + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + OMPL_CLASS_FORWARD(SpaceInformation); + /// @endcond + + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::StatePropagator */ + OMPL_CLASS_FORWARD(StatePropagator); + /// @endcond + + /** \class ompl::base::StatePropagatorPtr + \brief A shared pointer wrapper for ompl::control::StatePropagator */ + + /** \brief Model the effect of controls on system states */ + class StatePropagator + { + public: + /** \brief Constructor */ + StatePropagator(SpaceInformation *si) : si_(si) + { + } + + /** \brief Constructor */ + StatePropagator(const SpaceInformationPtr &si) : si_(si.get()) + { + } + + virtual ~StatePropagator() = default; + + /** \brief Propagate from a state, given a control, for some specified amount of time (the amount of time + can + also be negative, if canPropagateBackward() returns true) + \param state the state to start propagating from + \param control the control to apply + \param duration the duration for which the control is applied + \param result the state the system is brought to + + \note This function is not used for integration + internally. If integrating a system of differential + equations is needed, this should be implemented inside + the propagate() function. + + \note The pointer to the starting state and the result + state may be the same. + */ + virtual void propagate(const base::State *state, const Control *control, double duration, + base::State *result) const = 0; + + /** \brief Some systems can only propagate forward in time (i.e., the \e duration argument for the + propagate() + function is always positive). If this is the case, this function should return false. Planners that need + backward propagation (negative durations) will call this function to check. If backward propagation is + possible, this function should return true (this is the default). */ + virtual bool canPropagateBackward() const + { + return true; + } + + /** \brief Compute the control that can take the system from state \e from to state \e to. + Store that control in \e result; the duration for which the control should be applied is returned; + return < 0.0 if the computation was successful; return the control duration otherwise; + + \note If a negative value is returned, the content of \e result may have been changed, + but it does not represent a solution; */ + virtual double steer(const base::State * /*from*/, const base::State * /*to*/, Control * /*result*/) const + { + return -1.0; + } + + /** \brief Return true if the steer() function has been implemented */ + virtual bool canSteer() const + { + return false; + } + + protected: + /** \brief The instance of space information this state propagator operates on */ + SpaceInformation *si_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SteeredControlSampler.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SteeredControlSampler.h new file mode 100644 index 00000000..fa568c5a --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SteeredControlSampler.h @@ -0,0 +1,80 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Mark Moll, Ioan Sucan */ + +#ifndef OMPL_CONTROL_STEERED_CONTROL_SAMPLER_ +#define OMPL_CONTROL_STEERED_CONTROL_SAMPLER_ + +#include "ompl/control/DirectedControlSampler.h" +#include "ompl/control/StatePropagator.h" +#include "ompl/control/SpaceInformation.h" +#include + +namespace ompl +{ + namespace control + { + /** \brief Abstract definition of a steered control sampler. It uses the + steering function in a state propagator to find the controls that + drive from one state to another. */ + class SteeredControlSampler : public DirectedControlSampler + { + public: + /** \brief Constructor takes the state space to construct samples for as argument */ + SteeredControlSampler(const SpaceInformation *si) : DirectedControlSampler(si) + { + } + + ~SteeredControlSampler() override = default; + + unsigned int sampleTo(Control *control, const base::State *source, base::State *dest) override + { + double duration = si_->getStatePropagator()->steer(source, dest, control); + if (duration < std::numeric_limits::epsilon()) + return 0; + unsigned int steps = std::floor(duration / si_->getPropagationStepSize() + 0.5); + return si_->propagateWhileValid(source, control, std::max(1u, steps), dest); + } + + unsigned int sampleTo(Control *control, const Control * /*previous*/, const base::State *source, + base::State *dest) override + { + return sampleTo(control, source, dest); + } + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/PlannerIncludes.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/PlannerIncludes.h new file mode 100644 index 00000000..a0235252 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/PlannerIncludes.h @@ -0,0 +1,46 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_PLANNERS_PLANNER_INCLUDES_ +#define OMPL_CONTROL_PLANNERS_PLANNER_INCLUDES_ + +#include "ompl/base/Planner.h" +#include "ompl/control/SpaceInformation.h" +#include "ompl/control/PathControl.h" +#include "ompl/control/PlannerData.h" +#include "ompl/util/RandomNumbers.h" + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/est/EST.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/est/EST.h new file mode 100644 index 00000000..325e054b --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/est/EST.h @@ -0,0 +1,264 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2011, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ryan Luna */ + +#ifndef OMPL_CONTROL_PLANNERS_EST_EST_ +#define OMPL_CONTROL_PLANNERS_EST_EST_ + +#include "ompl/datastructures/Grid.h" +#include "ompl/control/planners/PlannerIncludes.h" +#include "ompl/base/ProjectionEvaluator.h" +#include "ompl/datastructures/PDF.h" +#include +#include + +namespace ompl +{ + namespace control + { + /** + @anchor cEST + @par Short description + EST is a tree-based motion planner that attempts to detect + the less explored area of the space through the use of a + grid imposed on a projection of the state space. Using this + information, EST continues tree expansion primarily from + less explored areas. It is important to set the projection + the algorithm uses (setProjectionEvaluator() function). If + no projection is set, the planner will attempt to use the + default projection associated to the state space. An + exception is thrown if no default projection is available + either. + @par External documentation + D. Hsu, J.-C. Latombe, and R. Motwani, Path planning in expansive configuration spaces, + Intl. J. Computational Geometry and Applications, + vol. 9, no. 4-5, pp. 495–512, 1999. DOI: + [10.1142/S0218195999000285](http://dx.doi.org/10.1142/S0218195999000285)
+ [[PDF]](http://bigbird.comp.nus.edu.sg/pmwiki/farm/motion/uploads/Site/ijcga96.pdf) + */ + + /** \brief Expansive Space Trees */ + class EST : public base::Planner + { + public: + /** \brief Constructor */ + EST(const SpaceInformationPtr &si); + + ~EST() override; + + base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override; + + void clear() override; + + /** \brief In the process of randomly selecting states in + the state space to attempt to go towards, the + algorithm may in fact choose the actual goal state, if + it knows it, with some probability. This probability + is a real number between 0.0 and 1.0; its value should + usually be around 0.05 and should not be too large. It + is probably a good idea to use the default value. */ + void setGoalBias(double goalBias) + { + goalBias_ = goalBias; + } + + /** \brief Get the goal bias the planner is using */ + double getGoalBias() const + { + return goalBias_; + } + + /** \brief Set the range the planner is supposed to use. + + This parameter greatly influences the runtime of the + algorithm. It represents the maximum length of a + motion to be added in the tree of motions. */ + void setRange(double distance) + { + maxDistance_ = distance; + } + + /** \brief Get the range the planner is using */ + double getRange() const + { + return maxDistance_; + } + + /** \brief Set the projection evaluator. This class is + able to compute the projection of a given state. */ + void setProjectionEvaluator(const base::ProjectionEvaluatorPtr &projectionEvaluator) + { + projectionEvaluator_ = projectionEvaluator; + } + + /** \brief Set the projection evaluator (select one from + the ones registered with the state space). */ + void setProjectionEvaluator(const std::string &name) + { + projectionEvaluator_ = si_->getStateSpace()->getProjection(name); + } + + /** \brief Get the projection evaluator */ + const base::ProjectionEvaluatorPtr &getProjectionEvaluator() const + { + return projectionEvaluator_; + } + + void setup() override; + + void getPlannerData(base::PlannerData &data) const override; + + protected: + /** \brief Representation of a motion + + This only contains pointers to parent motions as we + only need to go backwards in the tree. */ + class Motion + { + public: + Motion() = default; + + /** \brief Constructor that allocates memory for the state and the control */ + Motion(const SpaceInformation *si) : state(si->allocState()), control(si->allocControl()) + { + } + + ~Motion() = default; + + /** \brief The state contained by the motion */ + base::State *state{nullptr}; + + /** \brief The control contained by the motion */ + Control *control{nullptr}; + + /** \brief The number of steps the control is applied for */ + unsigned int steps{0}; + + /** \brief The parent motion in the exploration tree */ + Motion *parent{nullptr}; + }; + + struct MotionInfo; + + /** \brief A grid cell */ + using GridCell = Grid::Cell; + + /** \brief A PDF of grid cells */ + using CellPDF = PDF; + + /** \brief A struct containing an array of motions and a corresponding PDF element */ + struct MotionInfo + { + Motion *operator[](unsigned int i) + { + return motions_[i]; + } + const Motion *operator[](unsigned int i) const + { + return motions_[i]; + } + void push_back(Motion *m) + { + motions_.push_back(m); + } + unsigned int size() const + { + return motions_.size(); + } + bool empty() const + { + return motions_.empty(); + } + std::vector motions_; + CellPDF::Element *elem_; + }; + + /** \brief The data contained by a tree of exploration */ + struct TreeData + { + TreeData() = default; + + /** \brief A grid where each cell contains an array of motions */ + Grid grid{0}; + + /** \brief The total number of motions in the grid */ + unsigned int size{0}; + }; + + /** \brief Free the memory allocated by this planner */ + void freeMemory(); + + /** \brief Add a motion to the exploration tree */ + void addMotion(Motion *motion); + + /** \brief Select a motion to continue the expansion of the tree from */ + Motion *selectMotion(); + + /** \brief Valid state sampler */ + base::ValidStateSamplerPtr sampler_; + + /** \brief Directed control sampler */ + DirectedControlSamplerPtr controlSampler_; + + /** \brief The base::SpaceInformation cast as control::SpaceInformation, for convenience */ + const SpaceInformation *siC_; + + /** \brief The exploration tree constructed by this algorithm */ + TreeData tree_; + + /** \brief This algorithm uses a discretization (a grid) to guide the exploration. The exploration is + * imposed on a projection of the state space. */ + base::ProjectionEvaluatorPtr projectionEvaluator_; + + /** \brief The fraction of time the goal is picked as the state to expand towards (if such a state is + * available) */ + double goalBias_{0.05}; + + /** \brief The maximum length of a motion to be added to a tree */ + double maxDistance_{0.}; + + /** \brief The random number generator */ + RNG rng_; + + /** \brief The PDF used for selecting a cell from which to sample a motion */ + CellPDF pdf_; + + /** \brief The most recent goal motion. Used for PlannerData computation */ + Motion *lastGoalMotion_{nullptr}; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/kpiece/KPIECE1.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/kpiece/KPIECE1.h new file mode 100644 index 00000000..2f29098d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/kpiece/KPIECE1.h @@ -0,0 +1,432 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2010, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Ioan Sucan */ + +#ifndef OMPL_CONTROL_PLANNERS_KPIECE_KPIECE1_ +#define OMPL_CONTROL_PLANNERS_KPIECE_KPIECE1_ + +#include "ompl/control/planners/PlannerIncludes.h" +#include "ompl/base/ProjectionEvaluator.h" +#include "ompl/datastructures/GridB.h" +#include +#include + +namespace ompl +{ + namespace control + { + /** + @anchor cKPIECE1 + @par Short description + KPIECE is a tree-based planner that uses a discretization + (multiple levels, in general) to guide the exploration of + the continuous space. This implementation is a simplified + one, using a single level of discretization: one grid. The + grid is imposed on a projection of the state space. When + exploring the space, preference is given to the boundary of + this grid. The boundary is computed to be the set of grid + cells that have less than 2n non-diagonal neighbors in an + n-dimensional projection space. + It is important to set the projection the algorithm uses + (setProjectionEvaluator() function). If no projection is + set, the planner will attempt to use the default projection + associated to the state space. An exception is thrown if + no default projection is available either. + This implementation is intended for systems with differential constraints. + @par External documentation + I.A. Şucan and L.E. Kavraki, Kinodynamic motion planning by interior-exterior cell exploration, + in Workshop on the Algorithmic Foundations of Robotics, Dec. 2008.
+ [[PDF]](http://ioan.sucan.ro/files/pubs/wafr2008.pdf) + */ + + /** \brief Kinodynamic Planning by Interior-Exterior Cell Exploration */ + class KPIECE1 : public base::Planner + { + public: + /** \brief Constructor */ + KPIECE1(const SpaceInformationPtr &si); + + ~KPIECE1() override; + + base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override; + + void clear() override; + + /** In the process of randomly selecting states in the state + space to attempt to go towards, the algorithm may in fact + choose the actual goal state, if it knows it, with some + probability. This probability is a real number between 0.0 + and 1.0; its value should usually be around 0.05 and + should not be too large. It is probably a good idea to use + the default value. */ + void setGoalBias(double goalBias) + { + goalBias_ = goalBias; + } + + /** Get the goal bias the planner is using */ + double getGoalBias() const + { + return goalBias_; + } + + /** \brief Set the fraction of time for focusing on the + border (between 0 and 1). This is the minimum fraction + used to select cells that are exterior (minimum + because if 95% of cells are on the border, they will + be selected with 95% chance, even if this fraction is + set to 90%)*/ + void setBorderFraction(double bp) + { + selectBorderFraction_ = bp; + } + + /** \brief Get the fraction of time to focus exploration + on boundary */ + double getBorderFraction() const + { + return selectBorderFraction_; + } + + /** \brief When extending a motion from a cell, the + extension can be successful or it can fail. If the + extension is successful, the score of the cell is + multiplied by \e good. If the extension fails, the + score of the cell is multiplied by \e bad. These + numbers should be in the range (0, 1]. */ + void setCellScoreFactor(double good, double bad) + { + setGoodCellScoreFactor(good); + setBadCellScoreFactor(bad); + } + + /** \brief Set the factor that is to be applied to a cell's score when an expansion from that cell fails */ + void setBadCellScoreFactor(double bad) + { + badScoreFactor_ = bad; + } + + /** \brief Set the factor that is to be applied to a cell's score when an expansion from that cell succeedes + */ + void setGoodCellScoreFactor(double good) + { + goodScoreFactor_ = good; + } + + /** \brief Get the factor that is multiplied to a cell's + score if extending a motion from that cell succeeded. */ + double getGoodCellScoreFactor() const + { + return goodScoreFactor_; + } + + /** \brief Get the factor that is multiplied to a cell's + score if extending a motion from that cell failed. */ + double getBadCellScoreFactor() const + { + return badScoreFactor_; + } + + /** \brief When motions reach close to the goal, they are stored in a separate queue + to allow biasing towards the goal. This function sets the maximum size of that queue. */ + void setMaxCloseSamplesCount(unsigned int nCloseSamples) + { + nCloseSamples_ = nCloseSamples; + } + + /** \brief Get the maximum number of samples to store in the queue of samples that are close to the goal */ + unsigned int getMaxCloseSamplesCount() const + { + return nCloseSamples_; + } + + /** \brief Set the projection evaluator. This class is + able to compute the projection of a given state. */ + void setProjectionEvaluator(const base::ProjectionEvaluatorPtr &projectionEvaluator) + { + projectionEvaluator_ = projectionEvaluator; + } + + /** \brief Set the projection evaluator (select one from + the ones registered with the state space). */ + void setProjectionEvaluator(const std::string &name) + { + projectionEvaluator_ = si_->getStateSpace()->getProjection(name); + } + + /** \brief Get the projection evaluator */ + const base::ProjectionEvaluatorPtr &getProjectionEvaluator() const + { + return projectionEvaluator_; + } + + void setup() override; + void getPlannerData(base::PlannerData &data) const override; + + protected: + /** \brief Representation of a motion for this algorithm */ + struct Motion + { + Motion() = default; + + /** \brief Constructor that allocates memory for the state and the control */ + Motion(const SpaceInformation *si) : state(si->allocState()), control(si->allocControl()) + { + } + + ~Motion() = default; + + /** \brief The state contained by this motion */ + base::State *state{nullptr}; + + /** \brief The control contained by this motion */ + Control *control{nullptr}; + + /** \brief The number of steps the control is applied for */ + unsigned int steps{0}; + + /** \brief The parent motion in the exploration tree */ + Motion *parent{nullptr}; + }; + + /** \brief The data held by a cell in the grid of motions */ + struct CellData + { + CellData() = default; + + ~CellData() = default; + + /** \brief The set of motions contained in this grid cell */ + std::vector motions; + + /** \brief A measure of coverage for this cell. For + this implementation, this is the sum of motion + durations */ + double coverage{0.0}; + + /** \brief The number of times this cell has been + selected for expansion */ + unsigned int selections{1}; + + /** \brief A heuristic score computed based on + distance to goal (if available), successes and + failures at expanding from this cell. */ + double score{1.0}; + + /** \brief The iteration at which this cell was created */ + unsigned int iteration{0}; + + /** \brief The computed importance (based on other class members) */ + double importance{0.0}; + }; + + /** \brief Definintion of an operator passed to the Grid + structure, to order cells by importance */ + struct OrderCellsByImportance + { + bool operator()(const CellData *const a, const CellData *const b) const + { + return a->importance > b->importance; + } + }; + + /** \brief The datatype for the maintained grid datastructure */ + using Grid = GridB; + + /** \brief Information about a known good sample (closer to the goal than others) */ + struct CloseSample + { + /** \brief Constructor fully initializes the content of this structure */ + CloseSample(Grid::Cell *c, Motion *m, double d) : cell(c), motion(m), distance(d) + { + } + + /** \brief The cell of the motion that is close to the goal */ + Grid::Cell *cell; + + /** \brief The motion that is close to the goal */ + Motion *motion; + + /** \brief The distance to the goal. This value is increased over time, as the number of selections for + * this sample increases */ + double distance; + + /** \brief Sort samples in accordance to their distance to the goal */ + bool operator<(const CloseSample &other) const + { + return distance < other.distance; + } + }; + + /** \brief Bounded set of good samples */ + struct CloseSamples + { + /** \brief Construct an object to maintain a set of at most \e size samples */ + CloseSamples(unsigned int size) : maxSize(size) + { + } + + /** \brief Evaluate whether motion \e motion, part of + cell \e cell is good enough to be part of the set + of samples closest to the goal, given its distance + to the goal is \e distance. If so, add it to the + set and return true. Otherwise, return false.*/ + bool consider(Grid::Cell *cell, Motion *motion, double distance); + + /** \brief Select the top sample (closest to the goal) + and update its position in the set subsequently + (pretend the distance to the goal is + larger). Returns true if the sample selection is + successful. */ + bool selectMotion(Motion *&smotion, Grid::Cell *&scell); + + /** \brief Return true if samples can be selected from this set */ + bool canSample() const + { + return !samples.empty(); + } + + /** \brief Maximum number of samples to maintain */ + unsigned int maxSize; + + /** \brief The maintained samples */ + std::set samples; + }; + + /** \brief The data defining a tree of motions for this algorithm */ + struct TreeData + { + TreeData() = default; + + /** \brief A grid containing motions, imposed on a + projection of the state space */ + Grid grid{0}; + + /** \brief The total number of motions (there can be + multiple per cell) in the grid */ + unsigned int size{0}; + + /** \brief The number of iterations performed on this tree */ + unsigned int iteration{1}; + }; + + /** \brief This function is provided as a calback to the + grid datastructure to update the importance of a + cell */ + static void computeImportance(Grid::Cell *cell, void * /*unused*/) + { + CellData &cd = *(cell->data); + cd.importance = cd.score / ((cell->neighbors + 1) * cd.coverage * cd.selections); + } + + /** \brief Free all the memory allocated by this planner */ + void freeMemory(); + + /** \brief Free the memory for the motions contained in a grid */ + void freeGridMotions(Grid &grid); + + /** \brief Free the memory for the data contained in a grid cell */ + void freeCellData(CellData *cdata); + + /** \brief Free the memory for a motion */ + void freeMotion(Motion *motion); + + /** \brief Add a motion to the grid containing motions. As + a hint, \e dist specifies the distance to the goal + from the state of the motion being added. The function + Returns the number of cells created to accommodate the + new motion (0 or 1). */ + Grid::Cell *addMotion(Motion *motion, double dist); + + /** \brief Select a motion and the cell it is part of from + the grid of motions. This is where preference is given + to cells on the boundary of the grid.*/ + bool selectMotion(Motion *&smotion, Grid::Cell *&scell); + + /** \brief When generated motions are to be added to the tree of motions, they often need to be split, so + they don't cross cell boundaries. + Given that a motion starts out in the cell \e origin and it crosses the cells in \e coords[\e index] + through \e coords[\e last] (inclusively), + return the index of the state to be used in the next part of the motion (that is within a cell). This + will be a value between \e index and \e last. */ + unsigned int findNextMotion(const std::vector &coords, unsigned int index, unsigned int count); + + /** \brief A control sampler */ + ControlSamplerPtr controlSampler_; + + /** \brief The tree datastructure */ + TreeData tree_; + + /** \brief The base::SpaceInformation cast as control::SpaceInformation, for convenience */ + const SpaceInformation *siC_; + + /** \brief This algorithm uses a discretization (a grid) + to guide the exploration. The exploration is imposed + on a projection of the state space. */ + base::ProjectionEvaluatorPtr projectionEvaluator_; + + /** \brief When extending a motion from a cell, the + extension can be successful. If it is, the score of the + cell is multiplied by this factor. */ + double goodScoreFactor_{0.9}; + + /** \brief When extending a motion from a cell, the + extension can fail. If it is, the score of the cell is + multiplied by this factor. */ + double badScoreFactor_{0.45}; + + /** \brief When motions reach close to the goal, they are stored in a separate queue + to allow biasing towards the goal. This variable specifies the maximum number of samples + to keep in that queue. */ + unsigned int nCloseSamples_{30}; + + /** \brief The fraction of time to focus exploration on + the border of the grid. */ + double selectBorderFraction_{0.8}; + + /** \brief The fraction of time the goal is picked as the state to expand towards (if such a state is + * available) */ + double goalBias_{0.05}; + + /** \brief The random number generator */ + RNG rng_; + + /** \brief The most recent goal motion. Used for PlannerData computation */ + Motion *lastGoalMotion_{nullptr}; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/Automaton.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/Automaton.h new file mode 100644 index 00000000..a770110d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/Automaton.h @@ -0,0 +1,191 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly, Keliang He */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_AUTOMATON_ +#define OMPL_CONTROL_PLANNERS_LTL_AUTOMATON_ + +#include "ompl/control/planners/ltl/World.h" +#include "ompl/util/ClassForward.h" +#include "ompl/config.h" +#include +#include +#include +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::Automaton */ + OMPL_CLASS_FORWARD(Automaton); + /// @endcond + + /** \class ompl::control::AutomatonPtr + \brief A shared pointer wrapper for ompl::control::Automaton */ + + /** \brief A class to represent a deterministic finite automaton, + each edge of which corresponds to a World. + A system trajectory, by way of project() and worldAtRegion() + in PropositionalDecomposition, determines a sequence of Worlds, + which are read by an Automaton to determine whether a trajectory + satisfies a given specification. + + An automaton is meant to be run in a read-only fashion, i.e., + it does not keep track of an internal state and can be thought of + as a lookup table. */ + class Automaton + { + public: + /** \brief Each automaton state has a transition map, which maps from a + World to another automaton state. + A set \f$P\f$ of true propositions correponds to the formula + \f$\bigwedge_{p\in P} p\f$. */ + struct TransitionMap + { + /** \brief Returns the automaton state corresponding to a given + World in this transition map. + Returns -1 if no such transition exists. */ + int eval(const World &w) const; + + mutable std::unordered_map entries; + }; + + /** \brief Creates an automaton with a given number of propositions and states. */ + Automaton(unsigned int numProps, unsigned int numStates = 0); + +#if OMPL_HAVE_SPOT + /** \brief Creates an automaton with a given number of propositions from an LTL + formula using Spot. By default, formulas are assumed to be co-safe LTL + formulas. If isCosafe is set to false, the formula is assumed to be a safe + LTL formula. */ + Automaton(unsigned numProps, std::string formula, bool isCosafe = true); +#endif + + /** \brief Adds a new state to the automaton and returns an ID for it. */ + unsigned int addState(bool accepting = false); + + /** \brief Sets the accepting status of a given state. */ + void setAccepting(unsigned int s, bool a); + + /** \brief Returns whether a given state of the automaton is accepting. */ + bool isAccepting(unsigned int s) const; + + /** \brief Sets the start state of the automaton. */ + void setStartState(unsigned int s); + + /** \brief Returns the start state of the automaton. + Returns -1 if no start state has been set. */ + int getStartState() const; + + /** \brief Adds a given transition to the automaton. */ + void addTransition(unsigned int src, const World &w, unsigned int dest); + + /** \brief Runs the automaton from its start state, using + the values of propositions from a given sequence of Worlds. + Returns false if and only if the result is a nonexistent state + (i.e., if and only if there does not exist an extension to trace + that will lead it to an accepting state). */ + bool run(const std::vector &trace) const; + + /** \brief Runs the automaton for one step from the given state, + using the values of propositions from a given World. + Returns the resulting state, or -1 if the result is a nonexistent state. */ + int step(int state, const World &w) const; + + /** \brief Returns the outgoing transition map for a given automaton state. */ + TransitionMap &getTransitions(unsigned int src); + + /** \brief Returns the number of states in this automaton. */ + unsigned int numStates() const; + + /** \brief Returns the number of transitions in this automaton. */ + unsigned int numTransitions() const; + + /** \brief Returns the number of propositions used by this automaton. */ + unsigned int numProps() const; + + /** \brief Prints the automaton to a given output stream, in Graphviz dot format. */ + void print(std::ostream &out) const; + + /** \brief Returns the shortest number of transitions from a given state to + an accepting state. */ + unsigned int distFromAccepting(unsigned int s) const; + + /** \brief Returns a single-state automaton that accepts on all inputs. */ + static AutomatonPtr AcceptingAutomaton(unsigned int numProps); + + /** \brief Helper function to return a coverage automaton. + Assumes all propositions are mutually exclusive. */ + static AutomatonPtr CoverageAutomaton(unsigned int numProps, const std::vector &covProps); + + /** \brief Helper function to return a sequence automaton. + Assumes all propositions are mutually exclusive. */ + static AutomatonPtr SequenceAutomaton(unsigned int numProps, const std::vector &seqProps); + + /** \brief Helper function to return a disjunction automaton, + which accepts when one of the given propositions becomes true. */ + static AutomatonPtr DisjunctionAutomaton(unsigned int numProps, const std::vector &disjProps); + + /** \brief Returns an avoidance automaton, which rejects when any one of the + given list of propositions becomes true. Accepts otherwise. */ + static AutomatonPtr AvoidanceAutomaton(unsigned int numProps, const std::vector &avoidProps); + + /** \brief Helper function to return a coverage automaton + over propositions from 0 to numProps-1. + Assumes all propositions are mutually exclusive. */ + static AutomatonPtr CoverageAutomaton(unsigned int numProps); + + /** \brief Helper function to return a sequence automaton + over propositions from 0 to numProps-1, in that order. + Assumes all propositions are mutually exclusive. */ + static AutomatonPtr SequenceAutomaton(unsigned int numProps); + + /** \brief Helper function to return a disjunction automaton, + which accepts when one of the given propositions in [0,numProps-1] becomes true. */ + static AutomatonPtr DisjunctionAutomaton(unsigned int numProps); + + protected: + unsigned int numProps_; + unsigned int numStates_; + int startState_{-1}; + std::vector accepting_; + std::vector transitions_; + mutable std::vector distances_; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLPlanner.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLPlanner.h new file mode 100644 index 00000000..3cfbfe4d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLPlanner.h @@ -0,0 +1,210 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_LTLPLANNER_ +#define OMPL_CONTROL_PLANNERS_LTL_LTLPLANNER_ + +#include "ompl/control/planners/PlannerIncludes.h" +#include "ompl/control/planners/ltl/ProductGraph.h" +#include "ompl/control/planners/ltl/LTLSpaceInformation.h" +#include "ompl/datastructures/PDF.h" +#include +#include +#include + +namespace ompl +{ + namespace control + { + /** \anchor cLTLPlanner + \brief A planner for generating system trajectories to satisfy + a logical specification given by an automaton, the propositions + of which are defined over a decomposition of the system's state space. + + \todo cite papers */ + class LTLPlanner : public base::Planner + { + public: + /** \brief Create an LTLPlanner with a given space and product graph. + Accepts an optional third parameter to control how much time is spent + promoting low-level tree exploration along a given high-level lead. */ + LTLPlanner(const LTLSpaceInformationPtr &si, ProductGraphPtr a, double exploreTime = 0.5); + + /** \brief Clears all memory belonging to this LTLPlanner .*/ + ~LTLPlanner() override; + + /// @name ompl::base::Planner Interface + /// @{ + + /** \brief Initializes LTLPlanner data structures. */ + void setup() override; + + /** \brief Clears all datastructures belonging to this LTLPlanner. */ + void clear() override; + + /** \brief Continues solving until a solution is found + or a given planner termination condition is met. + Returns true if a solution was found. */ + base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override; + /// @} + + /** \brief Helper debug method to access this planner's + underlying tree of states. */ + void getTree(std::vector &tree) const; + + /** \brief Helper debug method to return the sequence of high-level product + graph states corresponding to a sequence of low-level continous system states, + beginning from an optional initial high-level state. */ + std::vector getHighLevelPath(const std::vector &path, + ProductGraph::State *start = nullptr) const; + + protected: + /** \brief Representation of a motion + + A motion contains pointers to its state, its parent motion, and the control + that was applied to get from its parent to its state. */ + struct Motion + { + public: + /** \brief Default constructor for Motion. */ + Motion() = default; + + /** \brief Constructor that allocates memory for the state and the control, + given a space. */ + Motion(const SpaceInformation *si); + + /** \brief Motion destructor does not clear memory. + Deletions should be performed by the LTLPlanner. */ + virtual ~Motion(); + + /** \brief The state contained by the motion */ + base::State *state{nullptr}; + + /** \brief The control contained by the motion */ + Control *control{nullptr}; + + /** \brief The parent motion in the tree */ + Motion *parent{nullptr}; + + /** \brief The number of steps for which the control is applied */ + unsigned int steps{0}; + + /** \brief The high-level state to which this motion belongs */ + ProductGraph::State *abstractState{nullptr}; + }; + + /** \brief A structure to hold measurement information for a high-level state, + as well as the set of tree motions belonging to that high-level state. + Exactly one ProductGraphStateInfo will exist for each ProductGraph::State. */ + struct ProductGraphStateInfo + { + /** \brief Creates an info object with no measurements and no tree motions. */ + ProductGraphStateInfo() = default; + + /** \brief Adds a tree motion to an info object. + This method is called whenever a new tree motion is created + in the high-level state corresponding to this info object. */ + void addMotion(Motion *m); + + double weight{0.}; + PDF motions; + std::unordered_map::Element *> motionElems; + double volume{0.}; + double autWeight{0.}; + unsigned int numSel{0}; + PDF::Element *pdfElem{nullptr}; + }; + + /** \brief Updates and returns the weight of an abstraction state. */ + virtual double updateWeight(ProductGraph::State *as); + + /** \brief Initializes the info object for a new high-level state. */ + virtual void initAbstractInfo(ProductGraph::State *as); + + /** \brief Compute a set of high-level states along a lead + to be considered for expansion. */ + virtual void buildAvail(const std::vector &lead); + + /** \brief Expand the tree of motions along a given lead + for a given duration of time. + Returns true if a solution was found, in which case the endpoint + of the solution trajectory will be stored in the given Motion pointer. + Otherwise, returns false. */ + virtual bool explore(const std::vector &lead, Motion *&soln, double duration); + + /** \brief Returns the weight of an edge between two given high-level states, + which we compute as the product of the reciprocals of the weights + of the two states. */ + virtual double abstractEdgeWeight(ProductGraph::State *a, ProductGraph::State *b) const; + + /** \brief State sampler */ + base::StateSamplerPtr sampler_; + + /** \brief Control sampler */ + ControlSamplerPtr controlSampler_; + + /** \brief Handle to the control::SpaceInformation object */ + const LTLSpaceInformation *ltlsi_; + + /** \brief The high level abstaction used to grow the tree structure */ + ProductGraphPtr abstraction_; + + /** \brief Used to sample nonempty regions in which to promote expansion. */ + PDF availDist_; + + /** \brief A random number generator. */ + RNG rng_; + + /** \brief Set of all motions. */ + std::vector motions_; + + /** \brief Start state in product graph. */ + ProductGraph::State *prodStart_{nullptr}; + + /** \brief Time to spend exploring each lead. */ + double exploreTime_; + + /** \brief Map of abstraction states to their details. */ + std::unordered_map abstractInfo_; + + private: + /** \brief Clears this planner's underlying tree of system states. */ + void clearMotions(); + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLProblemDefinition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLProblemDefinition.h new file mode 100644 index 00000000..7433807b --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLProblemDefinition.h @@ -0,0 +1,74 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2013, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_LTLPROBLEMDEFINITION_ +#define OMPL_CONTROL_PLANNERS_LTL_LTLPROBLEMDEFINITION_ + +#include "ompl/base/ProblemDefinition.h" +#include "ompl/control/planners/ltl/ProductGraph.h" +#include "ompl/control/planners/ltl/LTLSpaceInformation.h" + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::LTLProblemDefinition */ + OMPL_CLASS_FORWARD(LTLProblemDefinition); + /// @endcond + + /** \class ompl::control::LTLProblemDefinitionPtr + \brief A shared pointer wrapper for ompl::control::LTLProblemDefinition */ + class LTLProblemDefinition : public base::ProblemDefinition + { + public: + LTLProblemDefinition(const control::LTLSpaceInformationPtr <lsi); + + ~LTLProblemDefinition() override = default; + + void addLowerStartState(const base::State *s); + + base::PathPtr getLowerSolutionPath() const; + + protected: + void createGoal(); + + LTLSpaceInformationPtr ltlsi_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLSpaceInformation.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLSpaceInformation.h new file mode 100644 index 00000000..52e4ddfa --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLSpaceInformation.h @@ -0,0 +1,104 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2013, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_LTLSPACEINFORMATION_ +#define OMPL_CONTROL_PLANNERS_LTL_LTLSPACEINFORMATION_ + +#include "ompl/base/spaces/DiscreteStateSpace.h" +#include "ompl/control/SpaceInformation.h" +#include "ompl/control/planners/ltl/ProductGraph.h" + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::LTLSpaceInformation */ + OMPL_CLASS_FORWARD(LTLSpaceInformation); + /// @endcond + + /** \class ompl::control::LTLSpaceInformationPtr + \brief A shared pointer wrapper for ompl::control::LTLSpaceInformation */ + class LTLSpaceInformation : public SpaceInformation + { + public: + LTLSpaceInformation(const SpaceInformationPtr &si, const ProductGraphPtr &prod); + + ~LTLSpaceInformation() override = default; + + void setup() override; + + const ProductGraphPtr &getProductGraph() const + { + return prod_; + } + + const SpaceInformationPtr &getLowSpace() + { + return lowSpace_; + } + + void getFullState(const base::State *low, base::State *full); + + base::State *getLowLevelState(base::State *s); + const base::State *getLowLevelState(const base::State *s); + + ProductGraph::State *getProdGraphState(const base::State *s) const; + + protected: + enum SpaceIndex + { + LOW_LEVEL = 0, + REGION = 1, + COSAFE = 2, + SAFE = 3 + }; + // Creates a new state propagator which uses the user-defined propagator + // defined in low state space, followed by automaton-defined transition rules + // for the co-safe and safe automata in prod. + void extendPropagator(const SpaceInformationPtr &oldsi); + + // Creates a new state validity checker which uses the user-defined validity checker + // defined in low state space and also checks for valid states in the automata in prod. + void extendValidityChecker(const SpaceInformationPtr &oldsi); + + ProductGraphPtr prod_; + SpaceInformationPtr lowSpace_; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/ProductGraph.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/ProductGraph.h new file mode 100644 index 00000000..ffc05894 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/ProductGraph.h @@ -0,0 +1,258 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_PRODUCTGRAPH_ +#define OMPL_CONTROL_PLANNERS_LTL_PRODUCTGRAPH_ + +#include "ompl/base/State.h" +#include "ompl/control/planners/ltl/Automaton.h" +#include "ompl/control/planners/ltl/PropositionalDecomposition.h" +#include "ompl/util/ClassForward.h" +#include +#include +#include +#include +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::ProductGraph */ + OMPL_CLASS_FORWARD(ProductGraph); + /// @endcond + + /** \class ompl::control::ProductGraphPtr + \brief A shared pointer wrapper for ompl::control::ProductGraph */ + + /** \brief A ProductGraph represents the weighted, directed, graph-based + Cartesian product of a PropositionalDecomposition object, + an Automaton corresponding to a co-safe LTL specification, + and an Automaton corresponding to a safe LTL specification. */ + class ProductGraph + { + public: + class State; + + /// @cond IGNORE + /** \brief Hash function for State to be used in std::unordered_map */ + struct HashState + { + std::size_t operator()(const State &s) const; + }; + /// @endcond + + /** \brief A State of a ProductGraph represents a vertex in the graph-based + Cartesian product represented by the ProductGraph. + A State is simply a tuple consisting of a PropositionalDecomposition region, + a co-safe Automaton state, and a safe Automaton state. */ + class State + { + friend class ProductGraph; + + public: + /** \brief Creates a State without any assigned PropositionalDecomposition + region or Automaton states. All of these values are initialized to -1. */ + State() = default; + + /** \brief Basic copy constructor for State. */ + State(const State &s) = default; + + /** \brief Returns whether this State is equivalent to a given State, + by comparing their PropositionalDecomposition regions and + Automaton states. */ + bool operator==(const State &s) const; + + /** \brief Returns whether this State is valid. + A State is valid if and only if none of its Automaton states + are dead states (a dead state has value -1). */ + bool isValid() const; + + friend struct HashState; + + /** \brief Helper function to print this State to a given output stream. */ + friend std::ostream &operator<<(std::ostream &out, const State &s); + + /** \brief Returns this State's PropositionalDecomposition region component. */ + int getDecompRegion() const; + + /** \brief Returns this State's co-safe Automaton state component. */ + int getCosafeState() const; + + /** \brief Returns this State's safe Automaton state component. */ + int getSafeState() const; + + private: + int decompRegion{-1}; + int cosafeState{-1}; + int safeState{-1}; + }; + + /** \brief Initializes a ProductGraph with a given PropositionalDecomposition, + co-safe Automaton, and safe Automaton. */ + ProductGraph(PropositionalDecompositionPtr decomp, AutomatonPtr cosafetyAut, AutomatonPtr safetyAut); + + /** \brief Initializes an abstraction with a given propositional + decomposition and cosafety automaton. The safety automaton is + set to be one that always accepts. */ + ProductGraph(const PropositionalDecompositionPtr &decomp, AutomatonPtr cosafetyAut); + + ~ProductGraph(); + + /** \brief Returns the PropositionalDecomposition contained + within this ProductGraph. */ + const PropositionalDecompositionPtr &getDecomp() const; + + /** \brief Returns the co-safe Automaton contained + within this ProductGraph. */ + const AutomatonPtr &getCosafetyAutom() const; + + /** \brief Returns the safe Automaton contained + within this ProductGraph. */ + const AutomatonPtr &getSafetyAutom() const; + + /** \brief Returns a shortest-path sequence of ProductGraph states, beginning with + a given initial State and ending with a State for which + the corresponding safety Automaton state is accepting, + and the corresponding co-safety Automaton state is as close as possible + to an accepting state given the adjacency properties of the + PropositionalDecomposition. + Dijkstra's shortest-path algorithm is used to compute the path with + the given edge-weight function. */ + std::vector computeLead(State *start, const std::function &edgeWeight); + + /** \brief Clears all memory belonging to this ProductGraph. */ + void clear(); + + /** \brief Constructs this ProductGraph beginning with a given initial State, + using a breadth-first search. Accepts an optional initialization method, + which will be called exactly once on each State (including the given initial State) + that is added to the ProductGraph. + The default argument for the initialization method is a no-op method. */ + void buildGraph(State *start, const std::function &initialize = [](State *) {}); + + /** \brief Returns whether the given State is an accepting State + in this ProductGraph. + We call a State accepting if its safety Automaton state component + is accepting, and its co-safety Automaton state component + is as close as possible to an accepting state in the co-safety Automaton + given the adjacency properties of the PropositionalDecomposition. */ + bool isSolution(const State *s) const; + + /** \brief Returns the initial State of this ProductGraph. */ + State *getStartState() const; + + /** \brief Helper method to return the volume of the PropositionalDecomposition + region corresponding to the given ProductGraph State. */ + double getRegionVolume(const State *s); + + /** \brief Helper method to return the distance from a given State's + co-safety state to an accepting state in the co-safety Automaton. */ + int getCosafeAutDistance(const State *s) const; + + /** \brief Helper method to return the distance from a given State's + safety state to an accepting state in the safety Automaton. */ + int getSafeAutDistance(const State *s) const; + + /** \brief Returns a ProductGraph State with initial co-safety and safety + Automaton states, and the PropositionalDecomposition region that contains + a given base::State. */ + State *getState(const base::State *cs) const; + + /** \brief Returns a ProductGraph State with given co-safety and safety + Automaton states, and the PropositionalDecomposition region that contains + a given base::State. */ + State *getState(const base::State *cs, int cosafe, int safe) const; + + /** \brief Returns a ProductGraph State with a given PropositionalDecomposition region. + The co-safety and safety Automaton states are calculated using a given parent + ProductGraph State and the decomposition region. */ + State *getState(const State *parent, int nextRegion) const; + + /** \brief Returns a ProductGraph state with the PropositionalDecomposition region + that contains a given base::State. + The co-safety and safety Automaton states are calculated using a given parent + ProductGraph State and the decomposition region. */ + State *getState(const State *parent, const base::State *cs) const; + + /** \brief Returns the ProductGraph state corresponding to the given region, + co-safety state, and safety state. */ + State *getState(int region, int cosafe, int safe) const + { + State s; + s.decompRegion = region; + s.cosafeState = cosafe; + s.safeState = safe; + State *&ret = stateToPtr_[s]; + if (ret == nullptr) + ret = new State(s); + return ret; + } + + protected: + struct Edge + { + double cost = {0}; + }; + + using GraphType = boost::adjacency_list; + using Vertex = boost::graph_traits::vertex_descriptor; + using VertexIter = boost::graph_traits::vertex_iterator; + using VertexIndexMap = boost::property_map::type; + using EdgeIter = boost::graph_traits::edge_iterator; + + PropositionalDecompositionPtr decomp_; + AutomatonPtr cosafety_; + AutomatonPtr safety_; + GraphType graph_; + State *startState_; + std::vector solutionStates_; + + /* Only one State pointer will be allocated for each possible State + in the ProductGraph. There will exist situations in which + all we have are the component values (region, automaton states) + of a State and we want the actual State pointer. + We use this map to access it. */ + mutable std::unordered_map stateToPtr_; + + /* Map from State pointer to the index of the corresponding vertex + in the graph. */ + std::unordered_map stateToIndex_; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/PropositionalDecomposition.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/PropositionalDecomposition.h new file mode 100644 index 00000000..23ed1173 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/PropositionalDecomposition.h @@ -0,0 +1,107 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_PROPOSITIONALDECOMPOSITION_ +#define OMPL_CONTROL_PLANNERS_LTL_PROPOSITIONALDECOMPOSITION_ + +#include "ompl/base/State.h" +#include "ompl/control/planners/syclop/Decomposition.h" +#include "ompl/control/planners/ltl/World.h" +#include "ompl/util/ClassForward.h" +#include "ompl/util/RandomNumbers.h" +#include "ompl/base/StateSampler.h" +#include + +namespace ompl +{ + namespace control + { + /// @cond IGNORE + /** \brief Forward declaration of ompl::control::PropositionalDecomposition */ + OMPL_CLASS_FORWARD(PropositionalDecomposition); + /// @endcond + + /** \class ompl::control::PropositionalDecompositionPtr + \brief A shared pointer wrapper for ompl::control::PropositionalDecomposition */ + + /** \brief A propositional decomposition wraps a given Decomposition + with a region-to-proposition assignment operator. + Each region in the decomposition has a corresponding World. */ + class PropositionalDecomposition : public Decomposition + { + public: + /** \brief Creates a propositional decomposition wrapped around a given decomposition + with a given number of propositions. */ + PropositionalDecomposition(const DecompositionPtr &decomp); + + /** \brief Clears all memory belonging to this propositional decomposition. */ + ~PropositionalDecomposition() override; + + /** \brief Returns the World corresponding to a given region. */ + virtual World worldAtRegion(int rid) = 0; + + /* \todo section off the below methods with a general description of + "wrapper methods that simply call the underlying decomposition */ + + /** \brief Returns the number of regions in this propositional decomposition's + underlying decomposition. */ + int getNumRegions() const override; + + /** \brief Returns the number of propositions in this propositional decomposition. */ + virtual int getNumProps() const = 0; + + /** \brief Returns the volume of a given region. */ + double getRegionVolume(int rid) override; + + /** \brief Returns the region of the underlying decomposition that contains + a given State. */ + int locateRegion(const base::State *s) const override; + + void project(const base::State *s, std::vector &coord) const override; + + void getNeighbors(int rid, std::vector &neighbors) const override; + + void sampleFromRegion(int rid, RNG &rng, std::vector &coord) const override; + + void sampleFullState(const base::StateSamplerPtr &sampler, const std::vector &coord, + base::State *s) const override; + + protected: + DecompositionPtr decomp_; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/World.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/World.h new file mode 100644 index 00000000..2f70f394 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/World.h @@ -0,0 +1,117 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Matt Maly */ + +#ifndef OMPL_CONTROL_PLANNERS_LTL_WORLD_ +#define OMPL_CONTROL_PLANNERS_LTL_WORLD_ + +#include +#include + +namespace ompl +{ + namespace control + { + class World; + } +} // namespace ompl + +/// @cond IGNORE +/** \brief Hash function for World to be used in std::unordered_map */ +namespace std +{ + template <> + struct hash + { + size_t operator()(const ompl::control::World &w) const; + }; +} // namespace std +/// @endcond + +namespace ompl +{ + namespace control + { + /** \brief A class to represent an assignment of boolean values to propositions. + A World can be partially restrictive, i.e., some propositions do not have to + be assigned a value, in which case it can take on any value. + Our notion of a World is similar to a set of truth assignments in propositional logic. */ + class World + { + public: + /** \brief Initializes a world with a given number of propositions. */ + World(unsigned int numProps); + + /** \brief Returns the boolean value of a given proposition in this World. + Reports an error if the proposition has not set in this World. */ + bool operator[](unsigned int i) const; + + /** \brief Returns the boolean value of a given proposition in this World. + Creates a boolean value for the proposition if one does not already exist. */ + bool &operator[](unsigned int i); + + /** \brief Returns the number of propositions declared for this World. + Not all of the propositions have necessarily been set. */ + unsigned int numProps() const; + + /** \brief Returns whether this World propositionally satisfies a given World w. + Specifically, returns true iff for every proposition p assigned in w, + p is assigned in this World and this[p] == w[p]. */ + bool satisfies(const World &w) const; + + /** \brief Returns a formatted string representation of this World, + as a conjunction of literals. */ + std::string formula() const; + + /** \brief Returns this World's underlying proposition-to-boolean + assignment map. */ + const std::unordered_map &props() const; + + /** \brief Returns whether this World is equivalent to a given World, + by comparing their truth assignment maps. */ + bool operator==(const World &w) const; + + /** \brief Clears this world's truth assignment. */ + void clear(); + + friend struct std::hash; + + protected: + unsigned int numProps_; + std::unordered_map props_; + }; + } // namespace control +} // namespace ompl +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/pdst/PDST.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/pdst/PDST.h new file mode 100644 index 00000000..b2ff3b46 --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/pdst/PDST.h @@ -0,0 +1,331 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2013, Rice University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Rice University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Jonathan Sobieski, Mark Moll */ + +#ifndef OMPL_CONTROL_PLANNERS_PDST_PDST_ +#define OMPL_CONTROL_PLANNERS_PDST_PDST_ + +#include + +#include "ompl/base/Planner.h" +#include "ompl/base/goals/GoalSampleableRegion.h" +#include "ompl/control/PathControl.h" +#include "ompl/control/PlannerData.h" +#include "ompl/datastructures/BinaryHeap.h" + +namespace ompl +{ + namespace control + { + /** + @anchor cPDST + @par Short description + PDST is a tree-based motion planner that attempts to detect + the less explored area of the space through the use of a + binary space partition of a projection of the state space. + Exploration is biased towards large cells with few path + segments. Unlike most tree-based planners which expand from + a randomly select endpoint of a path segment, PDST expands + from a randomly selected point along a deterministically + selected path segment. Because of this, it is recommended + to increase the min. and max. control duration using + ompl::control::SpaceInformation::setMinMaxControlDuration. + It is important to set the projection + the algorithm uses (setProjectionEvaluator() function). If + no projection is set, the planner will attempt to use the + default projection associated to the state space. An + exception is thrown if no default projection is available + either. + @par External documentation + A.M. Ladd and L.E. Kavraki, Motion planning in the presence + of drift, underactuation and discrete system changes, in + Robotics: Science and Systems I, pp. 233–241, MIT + Press, June 2005. + [[PDF]](http://www.roboticsproceedings.org/rss01/p31.pdf) + */ + + /// \brief Path-Directed Subdivision Tree + class PDST : public base::Planner + { + public: + PDST(const SpaceInformationPtr &si); + + ~PDST() override; + + base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override; + void clear() override; + void setup() override; + + /// Extracts the planner data from the priority queue into data. + void getPlannerData(base::PlannerData &data) const override; + + /// Set the projection evaluator. This class is able to compute the projection of a given state. + void setProjectionEvaluator(const base::ProjectionEvaluatorPtr &projectionEvaluator) + { + projectionEvaluator_ = projectionEvaluator; + } + + /// Set the projection evaluator (select one from the ones registered with the state space). + void setProjectionEvaluator(const std::string &name) + { + projectionEvaluator_ = si_->getStateSpace()->getProjection(name); + } + + /// Get the projection evaluator + const base::ProjectionEvaluatorPtr &getProjectionEvaluator() const + { + return projectionEvaluator_; + } + + /// \brief In the process of randomly selecting states in + /// the state space to attempt to go towards, the + /// algorithm may in fact choose the actual goal state, if + /// it knows it, with some probability. This probability + /// is a real number between 0.0 and 1.0; its value should + /// usually be around 0.05 and should not be too large. It + /// is probably a good idea to use the default value. */ + void setGoalBias(double goalBias) + { + goalBias_ = goalBias; + } + /// Get the goal bias the planner is using */ + double getGoalBias() const + { + return goalBias_; + } + + protected: + struct Cell; + struct Motion; + + /// Comparator used to order motions in the priority queue + struct MotionCompare + { + /// returns true if m1 is lower priority than m2 + bool operator()(Motion *p1, Motion *p2) const + { + // lowest priority means highest score + return p1->score() < p2->score(); + } + }; + + /// Class representing the tree of motions exploring the state space + struct Motion + { + public: + Motion(base::State *startState, base::State *endState, Control *control, unsigned int controlDuration, + double priority, Motion *parent) + : startState_(startState) + , endState_(endState) + , control_(control) + , controlDuration_(controlDuration) + , priority_(priority) + , parent_(parent) + , cell_(nullptr) + , heapElement_(nullptr) + , isSplit_(false) + { + } + /// constructor for start states + Motion(base::State *state) + : startState_(state) + , endState_(state) + , control_(nullptr) + , controlDuration_(0) + , priority_(0.) + , parent_(nullptr) + , cell_(nullptr) + , heapElement_(nullptr) + , isSplit_(false) + { + } + /// The score is used to order motions in a priority queue. + double score() const + { + return priority_ / cell_->volume_; + } + void updatePriority() + { + priority_ = priority_ * 2. + 1.; + } + + /// The starting point of this motion + base::State *startState_; + /// The state reached by this motion + base::State *endState_; + /// The control that was applied to arrive at this state from the parent + control::Control *control_; + /// The duration that the control was applied to arrive at this state from the parent + unsigned int controlDuration_; + /// Priority for selecting this path to extend from in the future + double priority_; + /// Parent motion from which this one started + Motion *parent_; + /// Pointer to the cell that contains this path + Cell *cell_; + /// Handle to the element of the priority queue for this Motion + BinaryHeap::Element *heapElement_; + /// Whether this motion is the result of a split operation, in which case + /// its endState_ and control_ should not be freed. + bool isSplit_; + }; + + /// Cell is a Binary Space Partition + struct Cell + { + Cell(double volume, base::RealVectorBounds bounds, unsigned int splitDimension = 0) + : volume_(volume) + , splitDimension_(splitDimension) + , splitValue_(0.0) + , left_(nullptr) + , right_(nullptr) + , bounds_(std::move(bounds)) + { + } + + ~Cell() + { + if (left_ != nullptr) + { + delete left_; + delete right_; + } + } + + /// Subdivides this cell + void subdivide(unsigned int spaceDimension); + + /// Locates the cell that this motion begins in + Cell *stab(const Eigen::Ref &projection) const + { + auto *containingCell = const_cast(this); + while (containingCell->left_ != nullptr) + { + if (projection[containingCell->splitDimension_] <= containingCell->splitValue_) + containingCell = containingCell->left_; + else + containingCell = containingCell->right_; + } + return containingCell; + } + /// Add a motion + void addMotion(Motion *motion) + { + motions_.push_back(motion); + motion->cell_ = this; + } + + /// Number of cells + unsigned int size() const + { + unsigned int sz = 1; + if (left_ != nullptr) + sz += left_->size() + right_->size(); + return sz; + } + + /// Volume of the cell + double volume_; + /// Dimension along which the cell is split into smaller cells + unsigned int splitDimension_; + /// The midpoint between the bounds_ at the splitDimension_ + double splitValue_; + /// The left child cell (nullptr for a leaf cell) + Cell *left_; + /// The right child cell (nullptr for a leaf cell) + Cell *right_; + /// A bounding box for this cell + base::RealVectorBounds bounds_; + /// The motions contained in this cell. Motions are stored only in leaf nodes. + std::vector motions_; + }; + + /// \brief Inserts the motion into the appropriate cells, splitting the motion as necessary. + /// \e motion is assumed to be fully contained within \e cell. + void addMotion(Motion *motion, Cell *cell, base::State *, base::State *, Eigen::Ref, + Eigen::Ref); + /// \brief Either update heap after motion's priority has changed or insert motion into heap. + void updateHeapElement(Motion *motion) + { + if (motion->heapElement_ != nullptr) + priorityQueue_.update(motion->heapElement_); + else + motion->heapElement_ = priorityQueue_.insert(motion); + } + /// \brief Select a state along motion and propagate a new motion from there. + /// Return nullptr if no valid motion could be generated starting at the + /// selected state. + Motion *propagateFrom(Motion *motion, base::State *, base::State *); + /// \brief Find the max. duration that the control_ in motion can be applied s.t. + /// the trajectory passes through state. This means that "ancestor" motions with + /// the same control_ are also considered. A pointer to the oldest ancestor with + /// the same control_ is returned. Upon return applying the control + /// \e ancestor->control_ for duration steps starting from the state + /// \e ancestor->startState_ should result in the state \e state. + unsigned int findDurationAndAncestor(Motion *motion, base::State *state, base::State *scratch, + Motion *&ancestor) const; + + void freeMemory(); + + /// State sampler + base::StateSamplerPtr sampler_; + /// Directed control sampler + DirectedControlSamplerPtr controlSampler_; + /// SpaceInformation convenience pointer + const SpaceInformation *siC_; + // Random number generator + RNG rng_; + /// \brief Vector holding all of the start states supplied for the problem + /// Each start motion is the root of its own tree of motions. + std::vector startMotions_; + /// Priority queue of motions + BinaryHeap priorityQueue_; + /// Binary Space Partition + Cell *bsp_{nullptr}; + /// Projection evaluator for the problem + base::ProjectionEvaluatorPtr projectionEvaluator_; + /// Number between 0 and 1 specifying the probability with which the goal should be sampled + double goalBias_{0.05}; + /// Objected used to sample the goal + base::GoalSampleableRegion *goalSampler_{nullptr}; + /// Iteration number and priority of the next Motion that will be generated + unsigned int iteration_{1}; + /// Closest motion to the goal + Motion *lastGoalMotion_{nullptr}; + }; + } // namespace control +} // namespace ompl + +#endif diff --git a/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/rrt/HyRRT.h b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/rrt/HyRRT.h new file mode 100644 index 00000000..9f86337d --- /dev/null +++ b/dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/rrt/HyRRT.h @@ -0,0 +1,421 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2025, University of Santa Cruz Hybrid Systems Laboratory + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the University of Santa Cruz nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ + +/* Author: Beverly Xu */ + +#ifndef OMPL_CONTROL_PLANNERS_RRT_HYRRT_ +#define OMPL_CONTROL_PLANNERS_RRT_HYRRT_ + +#include "ompl/base/spaces/RealVectorStateSpace.h" +#include "ompl/control/ControlSpace.h" +#include "ompl/control/spaces/RealVectorControlSpace.h" +#include "ompl/datastructures/NearestNeighbors.h" +#include "ompl/control/planners/PlannerIncludes.h" +#include "ompl/control/Control.h" +#include "ompl/base/spaces/HybridStateSpace.h" + +using namespace std; + +namespace ompl +{ + namespace control + { + /** + @anchor HyRRT + @par Hybrid RRT (HyRRT) is an RRT algorithm that solves separate optimization + problems associated with the flows and jumps of the systems, to solve a + variety of robotic motion planning problems. As an RRT algorithm, HyRRT is + probabilistically-complete. The logical flow of the algorithm is as follows: + 1. Initialize the tree with a start state. + 2. While a solution has not been found: + a. Sample a random state. + b. Find the nearest state in the tree to the random state. + c. Extend from that state under either the flow or jump regimes, using + the continuous or discrete simulators, respectively. d. Continue until the + state is in collision, or the maximum flow time has been exceeded. e. If the + state is not within the unsafe set, add the state to the tree. If the state + is in collision, proceed to jump. + 3. Return the solution. + + @par External documentation: https://ieeexplore.ieee.org/document/9992444 + DOI: [10.1109/CDC51059.2022.9992444] + */ + + /** \brief Hybrid Rapidly-exploring Random Trees */ + class HyRRT : public base::Planner + { + public: + /** \brief Constructor */ + HyRRT(const control::SpaceInformationPtr &si); + + /** \brief Destructor */ + ~HyRRT() override; + + /** \brief Clear all allocated memory. */ + void clear() override; + + /** \brief Set the problem instance to solve */ + void setup() override; + + /** + * \brief Get the PlannerData object associated with this planner + * @param data the PlannerData object storing the edges and vertices of the solution + */ + void getPlannerData(base::PlannerData &data) const override; + base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override; + + /// \brief Representation of a motion in the search tree + class Motion + { + public: + /// \brief Default constructor + Motion() = default; + + /// \brief Constructor that allocates memory for the state + Motion(const control::SpaceInformation *si) : state(si->allocState()), control(si->allocControl()) + { + } + + /// \brief Destructor + ~Motion() = default; + + /// \brief The state contained by the motion + base::State *state{nullptr}; + + /// \brief The parent motion in the exploration tree + Motion *parent{nullptr}; + + /// \brief Pointer to the root of the tree this motion is + /// contained in. + const base::State *root{nullptr}; + + /// \brief The integration steps defining the solution pair of the motion, between the parent and child + /// vertices + std::vector *solutionPair{nullptr}; + + /** \brief The control contained by the motion */ + control::Control *control{nullptr}; + }; + + /** \brief Free the memory allocated by this planner */ + void freeMemory(); + + /** + * \brief Set the maximum time allocated to a full continuous simulator step. + * @param tM the maximum time allocated. Must be greater than 0, and greater than than the time + * allocated to a single continuous simulator call. + */ + void setTm(double tM) + { + if (tM <= 0) + throw Exception("Maximum flow time per propagation step must be greater than 0"); + if (!flowStepDuration_) + { + if (tM < flowStepDuration_) + throw Exception( + "Maximum flow time per propagation step must be greater than or equal to the length of time for each flow " + "integration step (flowStepDuration_)"); + } + tM_ = tM; + } + + /** + * \brief Set the time allocated to a single continuous simulator call, within the full period of a + * continuous simulator step. + * @param duration the time allocated per simulator step. Must be + * greater than 0 and less than the time allocated to a full continuous + * simulator step. + */ + void setFlowStepDuration(double duration) + { + if (duration <= 0) + throw Exception("Flow step length must be greater than 0"); + if (!tM_) + { + if (tM_ < duration) + throw Exception( + "Flow step length must be less than or equal to the maximum flow time per propagation step (Tm)"); + } + flowStepDuration_ = duration; + } + + /** + * \brief Define the jump set + * @param jumpSet the jump set associated with the hybrid system. + */ + void setJumpSet(std::function jumpSet) + { + jumpSet_ = jumpSet; + } + + /** + * \brief Define the flow set + * @param flowSet the flow set associated with the hybrid system. + */ + void setFlowSet(std::function flowSet) + { + flowSet_ = flowSet; + } + + /** + * \brief Define the unsafe set + * @param unsafeSet the unsafe set associated with the hybrid system. + */ + void setUnsafeSet(std::function unsafeSet) + { + unsafeSet_ = unsafeSet; + } + + /** + * \brief Define the distance measurement function + * @param function the distance function associated with the motion planning problem. + */ + void setDistanceFunction(std::function function) + { + distanceFunc_ = function; + } + + /** + * \brief Define the discrete dynamics simulator + * @param function the discrete simulator associated with the hybrid system. + */ + void setDiscreteSimulator( + std::function + function) + { + discreteSimulator_ = function; + } + + /** \brief Simulates the dynamics of the multicopter when in flow regime, with no nonnegligble forces other + * than input acceleration. */ + std::function + continuousSimulator = + [this](const control::Control *control, base::State *x_cur, double tFlow, base::State *new_state) + { + siC_->getStatePropagator()->propagate(x_cur, control, tFlow, new_state); + return new_state; + }; + + /** + * \brief Define the collision checker + * @param function the collision checker associated with the state space. Default is a point-by-point + * collision checker. + */ + void setCollisionChecker(std::function obstacleSet, + base::State *newState, double *collisionTime)> + function) + { + collisionChecker_ = function; + } + + /** \brief Set a different nearest neighbors datastructure */ + template