diff --git a/README.md b/README.md index 1bcb8565..3c0a1ea5 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,16 @@ CMVR-ES 工程。 +机械臂已提供独立的 OMPL RRTConnect 关节路径规划模块,构建与使用方式见 +[RRTConnect 接入说明](docs/ompl_rrt_connect.md)。`MotorRobotArm::moveP` 已接入路径规划、 +五次 B 样条平滑、运动限值校验与碰撞复检,并按控制周期下发电机指令。 + +运行时自碰撞监测位于 `cmvr-es/safety/self_collision`:`SelfCollisionMonitor` +通过 `RobotArm` 接口读取反馈、触发保护停止并协调恢复,碰撞计算仍由 +`algorithms/collision_detection` 中的 `CollisionChecker` 完成。 +`SelfCollisionTask` 仅绑定机械臂和转发周期调度;Monitor 不创建线程,恢复调用期间 +须继续周期检测。现有 `self_collision_task` 配置格式保持不变。 + ## 安装 ### 1. 拉取 Git 子模块 diff --git a/cmvr-es/CMakeLists.txt b/cmvr-es/CMakeLists.txt index 0ff7c443..a42d0c1f 100644 --- a/cmvr-es/CMakeLists.txt +++ b/cmvr-es/CMakeLists.txt @@ -1,11 +1,15 @@ +add_subdirectory(curves) + add_subdirectory(common/base/logging) link_libraries(cmvr_es::logging) +add_subdirectory(environment) add_subdirectory(common) add_subdirectory(hardware) add_subdirectory(algorithms) add_subdirectory(simulate) add_subdirectory(devices) +add_subdirectory(safety) add_subdirectory(manager/device_manager) add_subdirectory(manager/media_source_hub) add_subdirectory(service/quic_edge) diff --git a/cmvr-es/algorithms/CMakeLists.txt b/cmvr-es/algorithms/CMakeLists.txt index 471f0dfe..0654fef5 100644 --- a/cmvr-es/algorithms/CMakeLists.txt +++ b/cmvr-es/algorithms/CMakeLists.txt @@ -1,4 +1,5 @@ -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..fd5a8547 100644 --- a/cmvr-es/algorithms/collision_detection/CMakeLists.txt +++ b/cmvr-es/algorithms/collision_detection/CMakeLists.txt @@ -1,48 +1,45 @@ -add_library(self_collision_checker SHARED - self_collision/src/self_collision_checker.cpp - self_collision/src/distance_sampling_policy.cpp +add_library(collision_checker SHARED + src/collision_checker.cpp + src/distance_sampling_policy.cpp ) -target_include_directories(self_collision_checker PUBLIC +target_include_directories(collision_checker PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ) -target_compile_definitions(self_collision_checker PRIVATE - PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION - PINOCCHIO_WITH_HPP_FCL +target_compile_definitions(collision_checker PRIVATE COAL_DISABLE_HPP_FCL_WARNINGS ) -target_link_libraries(self_collision_checker PUBLIC - pinocchio_default - pinocchio_parsers - pinocchio_collision - coal +target_link_libraries(collision_checker PUBLIC + cmvr_es::environment + cmvr_es::proto ) +target_link_libraries(collision_checker PRIVATE coal) -add_library(cmvr_es::self_collision_checker ALIAS self_collision_checker) +add_library(cmvr_es::collision_checker ALIAS collision_checker) -add_executable(self_collision_checker_test - self_collision/test/self_collision_checker_test.cpp +add_executable(collision_checker_test + test/collision_checker_test.cpp ) -target_link_libraries(self_collision_checker_test PRIVATE - cmvr_es::self_collision_checker +target_link_libraries(collision_checker_test PRIVATE + cmvr_es::collision_checker gtest gtest_main pthread ) -target_compile_definitions(self_collision_checker_test PRIVATE +target_compile_definitions(collision_checker_test PRIVATE CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" ) add_executable(self_collision_benchmark - self_collision/benchmark/self_collision_benchmark.cpp + benchmark/collision_benchmark.cpp ) target_link_libraries(self_collision_benchmark PRIVATE - cmvr_es::self_collision_checker + cmvr_es::collision_checker ) target_compile_definitions(self_collision_benchmark PRIVATE CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" ) -install(TARGETS self_collision_checker LIBRARY DESTINATION lib) +install(TARGETS collision_checker LIBRARY DESTINATION lib) diff --git a/cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp similarity index 93% rename from cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp rename to cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp index dae09d71..17c1b8e8 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp +++ b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp @@ -4,7 +4,7 @@ #include #include -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" +#include "algorithms/collision_detection/include/collision_checker.h" int main() { @@ -15,7 +15,7 @@ int main() "R_WRIST_P", "R_WRIST_Y", "R_WRIST_R", }; - cmvr::SelfCollisionChecker checker; + cmvr::CollisionChecker checker; std::string error; if (!checker.init(urdf_path, joint_names, {}, &error)) { std::cerr << "Initialization failed: " << error << '\n'; 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/self_collision/include/distance_sampling_policy.h b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h similarity index 73% rename from cmvr-es/algorithms/collision_detection/self_collision/include/distance_sampling_policy.h rename to cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h index f2b022af..dbbbcd48 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/include/distance_sampling_policy.h +++ b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h @@ -3,8 +3,9 @@ #include #include +#include -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" +#include "environment/include/robot_model.h" namespace cmvr { @@ -20,22 +21,22 @@ public: bool configure(const DistanceSamplingOptions& options, std::string* error = nullptr); - bool shouldCheck(const CollisionGeometrySnapshot& current, + bool shouldCheck(const std::vector& current, Clock::time_point now) const; - void markChecked(const CollisionGeometrySnapshot& current, + void markChecked(const std::vector& current, Clock::time_point now); void reset(); double displacementSinceLastCheck( - const CollisionGeometrySnapshot& current) const; + const std::vector& current) const; bool hasBaseline() const { return has_baseline_; } private: DistanceSamplingOptions options_{}; - CollisionGeometrySnapshot last_checked_{}; + std::vector last_checked_{}; Clock::time_point last_check_time_{}; bool configured_{false}; bool has_baseline_{false}; diff --git a/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h b/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h deleted file mode 100644 index 60fae78b..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CMVR_ES_SELF_COLLISION_CHECKER_H -#define CMVR_ES_SELF_COLLISION_CHECKER_H - -#include -#include -#include -#include - -#include - -namespace cmvr { - -struct CollisionPair { - std::string first; - std::string second; -}; - -struct SelfCollisionOptions { - std::vector ignored_pairs; -}; - -struct CollisionObjectPose { - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - - std::size_t geometry_index{0}; - Eigen::Vector3d position{Eigen::Vector3d::Zero()}; - Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; - double bounding_radius_m{0.0}; -}; - -struct CollisionGeometrySnapshot { - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - - std::vector> objects; -}; - -struct SelfCollisionResult { - bool valid{false}; - bool in_collision{false}; - double minimum_distance_m{0.0}; - std::string first; - std::string second; - std::string error; -}; - -// Instances cache Pinocchio work data and are not thread-safe. -class SelfCollisionChecker { -public: - SelfCollisionChecker(); - ~SelfCollisionChecker(); - - SelfCollisionChecker(SelfCollisionChecker&&) noexcept; - SelfCollisionChecker& operator=(SelfCollisionChecker&&) noexcept; - - SelfCollisionChecker(const SelfCollisionChecker&) = delete; - SelfCollisionChecker& operator=(const SelfCollisionChecker&) = delete; - - bool init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error = nullptr); - - bool makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error = nullptr); - - SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot); - SelfCollisionResult check(const std::vector& joint_positions); - - 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_SELF_COLLISION_CHECKER_H diff --git a/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp b/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp deleted file mode 100644 index 8606bd22..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp +++ /dev/null @@ -1,403 +0,0 @@ -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -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 SelfCollisionChecker::Impl { -public: - bool init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error) - { - reset(); - if (urdf_path.empty()) { - setError(error, "URDF path is empty"); - return false; - } - if (!std::filesystem::is_regular_file(urdf_path)) { - setError(error, "URDF file does not exist: " + urdf_path); - return false; - } - if (active_joint_names.empty()) { - setError(error, "Active joint list is empty"); - return false; - } - - try { - pinocchio::urdf::buildModel(urdf_path, model_); - pinocchio::urdf::buildGeom( - model_, urdf_path, pinocchio::COLLISION, geometry_model_); - } catch (const std::exception& exception) { - setError(error, "Failed to load collision URDF: " + std::string(exception.what())); - reset(); - return false; - } - - if (geometry_model_.ngeoms == 0) { - setError(error, "URDF contains no collision geometry: " + urdf_path); - reset(); - return false; - } - - std::unordered_set active_joint_ids; - std::unordered_set unique_joint_names; - joint_names_.reserve(active_joint_names.size()); - joint_q_indices_.reserve(active_joint_names.size()); - for (const auto& joint_name : active_joint_names) { - if (joint_name.empty() || !unique_joint_names.insert(joint_name).second) { - setError(error, "Active joint names must be non-empty and unique"); - reset(); - return false; - } - if (!model_.existJointName(joint_name)) { - setError(error, "Joint not found in URDF: " + joint_name); - reset(); - return false; - } - const pinocchio::JointIndex joint_id = model_.getJointId(joint_name); - const auto& joint = model_.joints[joint_id]; - if (joint.nq() != 1) { - setError(error, "Only one-DoF active joints are supported: " + joint_name); - reset(); - return false; - } - active_joint_ids.insert(joint_id); - joint_names_.push_back(joint_name); - joint_q_indices_.push_back(joint.idx_q()); - } - - geometry_link_names_.resize(geometry_model_.ngeoms); - std::unordered_set selected_link_names; - for (pinocchio::GeomIndex geometry_id = 0; - geometry_id < geometry_model_.ngeoms; - ++geometry_id) { - auto& geometry = geometry_model_.geometryObjects[geometry_id]; - const std::string link_name = geometry.parentFrame < model_.frames.size() - ? model_.frames[geometry.parentFrame].name - : geometry.name; - geometry_link_names_[geometry_id] = link_name; - - const bool is_static = geometry.parentJoint == 0; - const bool belongs_to_active_arm = active_joint_ids.count(geometry.parentJoint) != 0; - if (!is_static && !belongs_to_active_arm) { - continue; - } - - if (!geometry.geometry) { - setError(error, "Collision geometry is null for link: " + link_name); - reset(); - return false; - } - geometry.geometry->computeLocalAABB(); - selected_geometry_indices_.push_back(geometry_id); - selected_link_names.insert(link_name); - } - - if (selected_geometry_indices_.size() < 2) { - setError(error, "Fewer than two collision geometries remain after arm filtering"); - reset(); - return false; - } - - std::set ignored_pairs; - for (const auto& pair : options.ignored_pairs) { - if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) { - setError(error, "Ignored collision pairs require two different non-empty links"); - reset(); - return false; - } - if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) { - setError(error, - "Ignored collision pair references an inactive or unknown link: " + - pair.first + ", " + pair.second); - reset(); - return false; - } - ignored_pairs.insert(canonicalPair(pair.first, pair.second)); - } - - geometry_model_.removeAllCollisionPairs(); - for (std::size_t first_index = 0; - first_index < selected_geometry_indices_.size(); - ++first_index) { - const auto first_geometry_id = selected_geometry_indices_[first_index]; - const auto& first_geometry = geometry_model_.geometryObjects[first_geometry_id]; - for (std::size_t second_index = first_index + 1; - second_index < selected_geometry_indices_.size(); - ++second_index) { - const auto second_geometry_id = selected_geometry_indices_[second_index]; - const auto& second_geometry = geometry_model_.geometryObjects[second_geometry_id]; - - if (first_geometry.parentJoint == second_geometry.parentJoint) { - continue; - } - if (model_.parents[first_geometry.parentJoint] == second_geometry.parentJoint || - model_.parents[second_geometry.parentJoint] == first_geometry.parentJoint) { - continue; - } - - const auto link_pair = canonicalPair( - geometry_link_names_[first_geometry_id], - geometry_link_names_[second_geometry_id]); - if (ignored_pairs.count(link_pair)) { - continue; - } - geometry_model_.addCollisionPair( - pinocchio::CollisionPair(first_geometry_id, second_geometry_id)); - } - } - - if (geometry_model_.collisionPairs.empty()) { - setError(error, "No active collision pairs remain after filtering"); - reset(); - return false; - } - - data_ = std::make_unique(model_); - geometry_data_ = std::make_unique(geometry_model_); - for (auto& request : geometry_data_->distanceRequests) { - request.enable_signed_distance = true; - } - neutral_q_ = pinocchio::neutral(model_); - initialized_ = true; - if (error) { - error->clear(); - } - return true; - } - - bool makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error) - { - if (!initialized_) { - setError(error, "SelfCollisionChecker is not initialized"); - return false; - } - if (!snapshot) { - setError(error, "Collision snapshot output is null"); - return false; - } - if (joint_positions.size() != joint_names_.size()) { - std::ostringstream stream; - stream << "Joint position size mismatch: expected " << joint_names_.size() - << ", got " << joint_positions.size(); - setError(error, stream.str()); - return false; - } - - Eigen::VectorXd q = neutral_q_; - for (std::size_t index = 0; index < joint_positions.size(); ++index) { - if (!std::isfinite(joint_positions[index])) { - setError(error, "Joint position contains a non-finite value: " + joint_names_[index]); - return false; - } - q[joint_q_indices_[index]] = joint_positions[index]; - } - - try { - pinocchio::updateGeometryPlacements( - model_, *data_, geometry_model_, *geometry_data_, q); - } catch (const std::exception& exception) { - setError(error, "Failed to update collision geometry: " + std::string(exception.what())); - return false; - } - - snapshot->objects.clear(); - snapshot->objects.reserve(selected_geometry_indices_.size()); - for (const auto geometry_id : selected_geometry_indices_) { - const auto& placement = geometry_data_->oMg[geometry_id]; - const auto& geometry = geometry_model_.geometryObjects[geometry_id]; - CollisionObjectPose pose; - pose.geometry_index = geometry_id; - pose.position = placement.translation(); - pose.orientation = Eigen::Quaterniond(placement.rotation()).normalized(); - pose.bounding_radius_m = std::max(0.0, geometry.geometry->aabb_radius); - snapshot->objects.push_back(std::move(pose)); - } - if (error) { - error->clear(); - } - return true; - } - - SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot) - { - SelfCollisionResult result; - if (!initialized_) { - result.error = "SelfCollisionChecker is not initialized"; - return result; - } - if (snapshot.objects.size() != selected_geometry_indices_.size()) { - result.error = "Collision snapshot size does not match initialized geometry"; - return result; - } - - for (std::size_t index = 0; index < snapshot.objects.size(); ++index) { - const auto& pose = snapshot.objects[index]; - if (pose.geometry_index != selected_geometry_indices_[index] || - pose.geometry_index >= geometry_data_->oMg.size()) { - result.error = "Collision snapshot geometry order is invalid"; - return result; - } - if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() || - pose.orientation.norm() <= std::numeric_limits::epsilon()) { - result.error = "Collision snapshot contains an invalid pose"; - return result; - } - geometry_data_->oMg[pose.geometry_index] = pinocchio::SE3( - pose.orientation.normalized().toRotationMatrix(), pose.position); - } - - try { - const std::size_t pair_index = - pinocchio::computeDistances(geometry_model_, *geometry_data_); - if (pair_index >= geometry_model_.collisionPairs.size()) { - result.error = "Collision distance computation returned no active pair"; - return result; - } - const auto& pair = geometry_model_.collisionPairs[pair_index]; - result.minimum_distance_m = geometry_data_->distanceResults[pair_index].min_distance; - result.first = geometry_link_names_[pair.first]; - result.second = geometry_link_names_[pair.second]; - result.in_collision = result.minimum_distance_m <= 0.0; - result.valid = std::isfinite(result.minimum_distance_m); - if (!result.valid) { - result.error = "Collision distance is not finite"; - } - } catch (const std::exception& exception) { - result.error = "Collision distance computation failed: " + std::string(exception.what()); - } - return result; - } - - SelfCollisionResult check(const std::vector& joint_positions) - { - CollisionGeometrySnapshot snapshot; - std::string error; - if (!makeSnapshot(joint_positions, &snapshot, &error)) { - SelfCollisionResult result; - result.error = std::move(error); - return result; - } - return check(snapshot); - } - - void reset() - { - initialized_ = false; - joint_names_.clear(); - joint_q_indices_.clear(); - selected_geometry_indices_.clear(); - geometry_link_names_.clear(); - geometry_data_.reset(); - data_.reset(); - model_ = pinocchio::Model{}; - geometry_model_ = pinocchio::GeometryModel{}; - neutral_q_.resize(0); - } - - bool initialized_{false}; - std::vector joint_names_; - std::vector joint_q_indices_; - std::vector selected_geometry_indices_; - std::vector geometry_link_names_; - pinocchio::Model model_; - pinocchio::GeometryModel geometry_model_; - std::unique_ptr data_; - std::unique_ptr geometry_data_; - Eigen::VectorXd neutral_q_; -}; - -SelfCollisionChecker::SelfCollisionChecker() - : impl_(std::make_unique()) -{ -} - -SelfCollisionChecker::~SelfCollisionChecker() = default; -SelfCollisionChecker::SelfCollisionChecker(SelfCollisionChecker&&) noexcept = default; -SelfCollisionChecker& SelfCollisionChecker::operator=(SelfCollisionChecker&&) noexcept = default; - -bool SelfCollisionChecker::init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error) -{ - return impl_->init(urdf_path, active_joint_names, options, error); -} - -bool SelfCollisionChecker::makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error) -{ - return impl_->makeSnapshot(joint_positions, snapshot, error); -} - -SelfCollisionResult SelfCollisionChecker::check(const CollisionGeometrySnapshot& snapshot) -{ - return impl_->check(snapshot); -} - -SelfCollisionResult SelfCollisionChecker::check(const std::vector& joint_positions) -{ - return impl_->check(joint_positions); -} - -bool SelfCollisionChecker::initialized() const -{ - return impl_->initialized_; -} - -std::size_t SelfCollisionChecker::dof() const -{ - return impl_->joint_names_.size(); -} - -std::size_t SelfCollisionChecker::activePairCount() const -{ - return impl_->geometry_model_.collisionPairs.size(); -} - -const std::vector& SelfCollisionChecker::jointNames() const -{ - return impl_->joint_names_; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp b/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp deleted file mode 100644 index 5c5d75b4..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include -#include -#include - -#include - -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.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"; -} - -SelfCollisionOptions gen2CollisionOptions() -{ - SelfCollisionOptions 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; -} - -CollisionGeometrySnapshot singleObjectSnapshot(double x, - double angle, - double radius) -{ - CollisionGeometrySnapshot snapshot; - CollisionObjectPose pose; - pose.geometry_index = 1; - pose.position = Eigen::Vector3d(x, 0.0, 0.0); - pose.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()); - pose.bounding_radius_m = radius; - snapshot.objects.push_back(pose); - return snapshot; -} - -TEST(SelfCollisionCheckerTest, LoadsRightArmFromDualArmUrdf) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - EXPECT_EQ(checker.dof(), 7U); - EXPECT_GT(checker.activePairCount(), 0U); - - CollisionGeometrySnapshot snapshot; - ASSERT_TRUE(checker.makeSnapshot(std::vector(7, 0.0), &snapshot, &error)) << error; - EXPECT_EQ(snapshot.objects.size(), 11U); - - const SelfCollisionResult result = checker.check(snapshot); - ASSERT_TRUE(result.valid) << result.error; - EXPECT_TRUE(result.first.rfind("L_", 0) != 0); - EXPECT_TRUE(result.second.rfind("L_", 0) != 0); -} - -TEST(SelfCollisionCheckerTest, RejectsWrongJointVectorSize) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - - CollisionGeometrySnapshot snapshot; - EXPECT_FALSE(checker.makeSnapshot(std::vector(6, 0.0), &snapshot, &error)); - EXPECT_NE(error.find("size mismatch"), std::string::npos); -} - -TEST(SelfCollisionCheckerTest, RemovesConfiguredIgnoredPair) -{ - SelfCollisionChecker baseline; - SelfCollisionChecker filtered; - std::string error; - ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - - SelfCollisionOptions 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(SelfCollisionCheckerTest, LoadsGen2RightArmCollisionModel) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init( - gen2CollisionUrdfPath(), - kGen2RightArmJoints, - gen2CollisionOptions(), - &error)) << error; - EXPECT_EQ(checker.dof(), 7U); - EXPECT_EQ(checker.activePairCount(), 19U); - - CollisionGeometrySnapshot snapshot; - ASSERT_TRUE(checker.makeSnapshot(kGen2SetupPose, &snapshot, &error)) << error; - EXPECT_EQ(snapshot.objects.size(), 8U); - - const SelfCollisionResult setup_result = checker.check(snapshot); - ASSERT_TRUE(setup_result.valid) << setup_result.error; - EXPECT_FALSE(setup_result.in_collision); - EXPECT_GT(setup_result.minimum_distance_m, 0.02); -} - -TEST(SelfCollisionCheckerTest, ClassifiesGen2SafetyDistances) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init( - gen2CollisionUrdfPath(), - kGen2RightArmJoints, - gen2CollisionOptions(), - &error)) << error; - - const SelfCollisionResult 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 SelfCollisionResult 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 SelfCollisionResult 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 SelfCollisionResult 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(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement) -{ - DistanceSamplingPolicy 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 = DistanceSamplingPolicy::Clock::now(); - const auto initial = singleObjectSnapshot(0.0, 0.0, 0.2); - EXPECT_TRUE(policy.shouldCheck(initial, start)); - policy.markChecked(initial, start); - - EXPECT_FALSE(policy.shouldCheck( - singleObjectSnapshot(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1))); - EXPECT_TRUE(policy.shouldCheck( - singleObjectSnapshot(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2))); - EXPECT_TRUE(policy.shouldCheck( - singleObjectSnapshot(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/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/self_collision/src/distance_sampling_policy.cpp b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp similarity index 80% rename from cmvr-es/algorithms/collision_detection/self_collision/src/distance_sampling_policy.cpp rename to cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp index e45df763..555e2372 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/src/distance_sampling_policy.cpp +++ b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp @@ -1,4 +1,4 @@ -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/distance_sampling_policy.h" #include #include @@ -46,7 +46,7 @@ bool DistanceSamplingPolicy::configure(const DistanceSamplingOptions& options, return true; } -bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& current, +bool DistanceSamplingPolicy::shouldCheck(const std::vector& current, const Clock::time_point now) const { if (!configured_ || !has_baseline_) { @@ -59,7 +59,7 @@ bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& curren return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m; } -void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& current, +void DistanceSamplingPolicy::markChecked(const std::vector& current, const Clock::time_point now) { last_checked_ = current; @@ -69,22 +69,22 @@ void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& curren void DistanceSamplingPolicy::reset() { - last_checked_.objects.clear(); + last_checked_.clear(); last_check_time_ = Clock::time_point{}; has_baseline_ = false; } double DistanceSamplingPolicy::displacementSinceLastCheck( - const CollisionGeometrySnapshot& current) const + const std::vector& current) const { - if (!has_baseline_ || current.objects.size() != last_checked_.objects.size()) { + 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.objects.size(); ++index) { - const auto& previous = last_checked_.objects[index]; - const auto& now = current.objects[index]; + 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(); } 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..d818a005 --- /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) +{ + DistanceSamplingPolicy 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 = DistanceSamplingPolicy::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/controllers/CMakeLists.txt b/cmvr-es/algorithms/controllers/CMakeLists.txt index 07fe6948..71fbc1b3 100644 --- a/cmvr-es/algorithms/controllers/CMakeLists.txt +++ b/cmvr-es/algorithms/controllers/CMakeLists.txt @@ -1,6 +1,3 @@ - -add_subdirectory(arm_control) - #find_package(VISP REQUIRED) # 如果报 relocation ... can not be used when making a shared object; recompile with -fPIC ,说明SRC 中包含了test文件 ,test diff --git a/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt b/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt deleted file mode 100644 index 3194deb1..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -add_library(arm_control SHARED - src/cartesian_velocity_controller.cpp -) - -target_include_directories(arm_control PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(arm_control - PUBLIC - cmvr_es::algorithms::arm_motion -) - -add_library(cmvr_es::algorithms::arm_control ALIAS arm_control) -install(TARGETS arm_control LIBRARY DESTINATION lib) - -add_executable(cartesian_velocity_controller_test src/cartesian_velocity_controller_test.cpp) -target_link_libraries(cartesian_velocity_controller_test PRIVATE - cmvr_es::algorithms::arm_control gtest gtest_main pthread) diff --git a/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h b/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h deleted file mode 100644 index cc6fc7ff..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H -#define CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "common/types/arm/arm_types.h" - -namespace cmvr::device { - -class CartesianVelocityController { -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; - - CartesianVelocityController(Config config, - std::shared_ptr planner, - std::size_t dof, - ReadStateCallback read_state, - SendVelocityCallback send_velocity); - ~CartesianVelocityController(); - - CartesianVelocityController(const CartesianVelocityController&) = delete; - CartesianVelocityController& operator=(const CartesianVelocityController&) = delete; - - Result speedL(const CartesianVelocity& velocity, - double acceleration, - double duration, - FrameType frame); - Result stop(std::optional acceleration = std::nullopt); - Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, - double duration, FrameType frame); - SpeedLReference getReference() const; - void shutdown(); - - bool busy() const { return busy_.load(); } - double stopTimeoutS() const { return config_.stop_timeout_s; } - CartesianVelocity getCommandTwistBase() const; - -private: - void ensureWorkerStarted_(); - void workerLoop_(); - void requestStop_(std::optional acceleration = std::nullopt); - void abortCommand_(); - void sendZero_(); - - 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_; - - std::unique_ptr worker_; - mutable std::mutex mutex_; - std::condition_variable cv_; - std::atomic stop_requested_{false}; - bool command_active_{false}; - CartesianVelocity target_twist_{}; - FrameType target_frame_{FrameType::Base}; - double target_acceleration_{0.25}; - SpeedLOptions target_options_{}; - SpeedLReference reference_{}; - CartesianVelocity command_twist_snapshot_{}; - std::uint64_t command_version_{0}; - std::atomic busy_{false}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H diff --git a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp b/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp deleted file mode 100644 index 073a7d47..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp +++ /dev/null @@ -1,379 +0,0 @@ -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" - -#include -#include -#include -#include - -#include "common/base/logging/logger.h" - -namespace cmvr::device { - -namespace { - -CartesianVelocityController::Config normalizeConfig(CartesianVelocityController::Config config) -{ - const CartesianVelocityController::Config defaults; - if (config.control_period_s <= 0.0) { - config.control_period_s = defaults.control_period_s; - } - if (config.stop_twist_norm <= 0.0) { - config.stop_twist_norm = defaults.stop_twist_norm; - } - if (config.stop_command_velocity_norm <= 0.0) { - config.stop_command_velocity_norm = defaults.stop_command_velocity_norm; - } - if (config.stop_measured_velocity_norm <= 0.0) { - config.stop_measured_velocity_norm = defaults.stop_measured_velocity_norm; - } - if (config.stop_acceleration <= 0.0) { - config.stop_acceleration = defaults.stop_acceleration; - } - if (!std::isfinite(config.stop_timeout_s) || config.stop_timeout_s <= 0.0) { - config.stop_timeout_s = defaults.stop_timeout_s; - } - return config; -} - -} // namespace - -CartesianVelocityController::CartesianVelocityController( - Config config, - std::shared_ptr planner, - const std::size_t dof, - ReadStateCallback read_state, - SendVelocityCallback send_velocity) - : config_(normalizeConfig(config)), - planner_(std::move(planner)), - dof_(dof), - read_state_(std::move(read_state)), - send_velocity_(std::move(send_velocity)) -{ -} - -CartesianVelocityController::~CartesianVelocityController() -{ - shutdown(); -} - -Result CartesianVelocityController::speedL(const CartesianVelocity& velocity, - const double acceleration, - const double duration, - const FrameType frame) -{ - SpeedLOptions options; - options.acceleration = acceleration; - return speedL(velocity, options, duration, frame); -} - -Result CartesianVelocityController::speedL(const CartesianVelocity& velocity, - const SpeedLOptions& options, - const double duration, const FrameType frame) -{ - const double acceleration = options.acceleration; - if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 || - !std::isfinite(acceleration) || acceleration <= 0.0 || - !std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) || - (options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) { - return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input"); - } - if (!worker_ || !worker_->joinable()) { - if (busy_.exchange(true)) { - return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); - } - } - - ensureWorkerStarted_(); - - std::uint64_t command_version = 0; - { - std::lock_guard lock(mutex_); - target_twist_ = velocity; - target_acceleration_ = acceleration; - target_frame_ = frame; - target_options_ = options; - reference_ = {}; - command_active_ = true; - busy_.store(true); - command_version = ++command_version_; - } - cv_.notify_all(); - - if (duration > 0.0) { - std::this_thread::sleep_for(std::chrono::duration(duration)); - bool should_stop = false; - { - std::lock_guard lock(mutex_); - if (command_version_ == command_version) { - target_twist_ = {}; - target_frame_ = FrameType::Base; - command_active_ = true; - ++command_version_; - should_stop = true; - } - } - if (should_stop) { - cv_.notify_all(); - } - } - return Result::success(); -} - -Result CartesianVelocityController::stop(const std::optional acceleration) -{ - if (!worker_ || !worker_->joinable()) { - return Result::success(); - } - // A completed speedL command leaves the worker thread joinable but idle. - // Do not turn that idle worker into a new command just because a caller - // requests a stop during a task transition. - if (!busy_.load()) { - return Result::success(); - } - requestStop_(acceleration); - return Result::success(); -} - -void CartesianVelocityController::shutdown() -{ - if (!worker_ || !worker_->joinable()) { - busy_.store(false); - return; - } - { - std::lock_guard lock(mutex_); - stop_requested_.store(true); - command_active_ = false; - target_twist_ = {}; - target_frame_ = FrameType::Base; - } - cv_.notify_all(); - worker_->join(); - worker_.reset(); - stop_requested_.store(false); - busy_.store(false); -} - -CartesianVelocity CartesianVelocityController::getCommandTwistBase() const -{ - std::lock_guard lock(mutex_); - return command_twist_snapshot_; -} - -SpeedLReference CartesianVelocityController::getReference() const -{ - std::lock_guard lock(mutex_); - return reference_; -} - -void CartesianVelocityController::ensureWorkerStarted_() -{ - if (worker_ && worker_->joinable()) { - return; - } - stop_requested_.store(false); - worker_ = std::make_unique(&CartesianVelocityController::workerLoop_, this); -} - -void CartesianVelocityController::workerLoop_() -{ - const double dt = config_.control_period_s; - auto next_tick = std::chrono::steady_clock::now(); - - while (true) { - CartesianVelocity target_twist; - double acceleration = 0.25; - FrameType target_frame = FrameType::Base; - SpeedLOptions options; - std::uint64_t applied_version = 0; - bool capture_reference = false; - { - std::unique_lock lock(mutex_); - cv_.wait(lock, [&]() { - return stop_requested_.load() || command_active_; - }); - if (stop_requested_.load()) { - break; - } - target_twist = target_twist_; - acceleration = target_acceleration_; - target_frame = target_frame_; - } - - next_tick = std::chrono::steady_clock::now(); - while (true) { - { - std::lock_guard lock(mutex_); - if (stop_requested_.load()) { - sendZero_(); - busy_.store(false); - return; - } - if (!command_active_) { - break; - } - target_twist = target_twist_; - acceleration = target_acceleration_; - target_frame = target_frame_; - options = target_options_; - options.acceleration = acceleration; - applied_version = command_version_; - capture_reference = options.capture_reference && !reference_.valid; - } - - if (!planner_->updateSpeedLLimits(options)) { - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] updateSpeedLAcceleration failed, acceleration=" - << acceleration; - requestStop_(); - continue; - } - - std::vector q_now; - std::vector qd_now; - if (!read_state_(q_now, qd_now)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] read_state failed"; - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - std::vector qd_cmd; - SpeedLReference reference; - if (capture_reference && - !planner_->captureSpeedLReference(q_now, target_twist, target_frame, reference)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] cannot capture motion reference"; - abortCommand_(); - break; - } - if (!planner_->speedLStep(target_twist, dt, q_now, qd_now, qd_cmd, target_frame)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] speedLStep failed, target_twist=[" - << target_twist.vx << ", " << target_twist.vy << ", " - << target_twist.vz << ", " << target_twist.wx << ", " - << target_twist.wy << ", " << target_twist.wz - << "], frame=" << (target_frame == FrameType::Tool ? "Tool" : "Base"); - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - JointVelocityCommand velocity_command; - velocity_command.velocity = qd_cmd; - const auto send_result = send_velocity_(velocity_command, acceleration); - if (!send_result.ok()) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: " - << send_result.message; - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - { - std::lock_guard lock(mutex_); - command_twist_snapshot_ = planner_->getSpeedLCommandTwistBase(); - if (capture_reference && command_version_ == applied_version) { - reference.command_version = applied_version; - reference_ = reference; - // Lock a captured Tool-frame translation in Base for the - // entire command, matching its distance reference axis. - target_twist_ = reference.target_base; - target_frame_ = FrameType::Base; - } - } - - if (twistNorm_(target_twist) < config_.stop_twist_norm && - velocityNorm_(qd_cmd) < config_.stop_command_velocity_norm && - velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) { - { - std::lock_guard lock(mutex_); - // A newer target may have arrived during planning/I/O. - if (command_version_ != applied_version) continue; - command_active_ = false; - // Serialize the final zero and busy transition with new - // submissions, not only the version comparison. - sendZero_(); - busy_.store(false); - } - break; - } - - next_tick += std::chrono::duration_cast( - std::chrono::duration(dt)); - std::this_thread::sleep_until(next_tick); - } - } - - sendZero_(); - busy_.store(false); -} - -void CartesianVelocityController::requestStop_(const std::optional acceleration) -{ - { - std::lock_guard lock(mutex_); - target_twist_ = {}; - target_frame_ = FrameType::Base; - target_acceleration_ = acceleration.has_value() ? *acceleration - : config_.stop_acceleration; - target_options_.acceleration = target_acceleration_; - target_options_.capture_reference = false; - command_active_ = true; - ++command_version_; - } - cv_.notify_all(); -} - -void CartesianVelocityController::abortCommand_() -{ - { - std::lock_guard lock(mutex_); - command_active_ = false; - target_twist_ = {}; - target_frame_ = FrameType::Base; - sendZero_(); - busy_.store(false); - } -} - -void CartesianVelocityController::sendZero_() -{ - if (!send_velocity_) { - return; - } - JointVelocityCommand zero; - zero.velocity.assign(dof_, 0.0); - (void)send_velocity_(zero, 0.0); -} - -double CartesianVelocityController::velocityNorm_(const std::vector& velocity) -{ - double value = 0.0; - for (const double item : velocity) { - value += item * item; - } - return std::sqrt(value); -} - -double CartesianVelocityController::twistNorm_(const CartesianVelocity& velocity) -{ - return std::sqrt(velocity.vx * velocity.vx + - velocity.vy * velocity.vy + - velocity.vz * velocity.vz + - velocity.wx * velocity.wx + - velocity.wy * velocity.wy + - velocity.wz * velocity.wz); -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp b/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp deleted file mode 100644 index daf2ed72..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" -#include -#include -#include -#include - -namespace cmvr::device { -namespace { -using namespace std::chrono_literals; -class Planner final : public CartesianMotionPlanner { -public: - bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; } - bool configureMoveL(const config::MoveLPlannerConfig&) override { return true; } - bool planMoveL(const CartesianPose&, const std::vector&, const std::vector&, - double, double, double, FrameType, CartesianJointTrajectory&) override { return false; } - bool updateSpeedLAcceleration(double) override { return true; } - bool updateSpeedLLimits(const SpeedLOptions& options) override { - applied_reversal.store(options.continuous_linear_reversal.value_or(false)); - applied_jerk.store(options.linear_jerk.value_or(10.0)); return true; - } - bool captureSpeedLReference(const std::vector&, const CartesianVelocity& target, - FrameType, SpeedLReference& ref) override { - ref.valid = true; - ref.tcp_pose_base.y = .5; - ref.target_base.vx = target.vy; - return true; - } - bool speedLStep(const CartesianVelocity& v, double, const std::vector&, - const std::vector&, std::vector& out, FrameType) override { - current = v; out = {v.vy}; return true; - } - CartesianVelocity getSpeedLCommandTwistBase() const override { return current; } - CartesianVelocity current; - std::atomic applied_jerk{0.0}; - std::atomic applied_reversal{false}; -}; -TEST(CartesianVelocityController, 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(); - CartesianVelocityController controller({}, planner, 1, - [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, - [&](const JointVelocityCommand& command, double) { - 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; - ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); - block_zero = true; - } - ASSERT_TRUE(controller.stop(3).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; })); - } - v.vy = -.08; - ASSERT_TRUE(controller.speedL(v, 3, 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(controller.busy()); - controller.shutdown(); -} -TEST(CartesianVelocityController, PublishesReferenceAfterSendAndKeepsCommandLimits) { - std::mutex mutex; - std::condition_variable cv; - bool entered = false, release = false; - auto planner = std::make_shared(); - CartesianVelocityController controller({}, planner, 1, - [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, - [&](const JointVelocityCommand&, double) { - 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(controller.speedL(v, options, 0, FrameType::Tool).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); - EXPECT_FALSE(controller.getReference().valid); - release = true; cv.notify_all(); - } - const auto deadline = std::chrono::steady_clock::now() + 1s; - while (!controller.getReference().valid && std::chrono::steady_clock::now() < deadline) - std::this_thread::sleep_for(1ms); - const auto ref = controller.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()); - controller.shutdown(); -} -TEST(CartesianVelocityController, RejectsInvalidMotionLimitsBeforeStarting) { - auto planner = std::make_shared(); - CartesianVelocityController controller({}, planner, 1, - [](auto&, auto&) { return false; }, - [](const auto&, double) { return Result::success(); }); - SpeedLOptions options; - options.linear_jerk = std::numeric_limits::quiet_NaN(); - EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok()); - options.linear_jerk = -1; - EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok()); - EXPECT_FALSE(controller.busy()); -} -} -} diff --git a/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h b/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h index 645ddd83..45cdedfa 100644 --- a/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h +++ b/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h @@ -9,7 +9,8 @@ #include "common/types/arm/arm_types.h" -namespace cmvr { +namespace cmvr +{ /** * @brief 基于相对 3D 位姿的 PBVS 控制器。 @@ -44,7 +45,6 @@ namespace cmvr { * 姿态误差: * * R_err = R_des * R_cur^T - * * e_R = Log(R_err)^vee * * 控制律: @@ -60,9 +60,11 @@ namespace cmvr { * - IK * - speedL 下发 */ -class PbvsController { +class PbvsController +{ public: - enum class ComputeStatus { + enum class ComputeStatus + { OK = 0, TARGET_NOT_SET, INVALID_INPUT, @@ -71,36 +73,25 @@ public: INVALID_CURRENT_POSE }; - struct Output { + struct Output + { // 当前位置误差,单位 m - Eigen::Vector3d position_error_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d position_error_G{Eigen::Vector3d::Zero()}; // 当前姿态误差 rotation-vector,单位 rad - Eigen::Vector3d rotation_error_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d rotation_error_G{Eigen::Vector3d::Zero()}; // PBVS 计算得到的原始线速度,单位 m/s - Eigen::Vector3d raw_linear_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d raw_linear_velocity_G{Eigen::Vector3d::Zero()}; // PBVS 计算得到的原始角速度,单位 rad/s - Eigen::Vector3d raw_angular_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d raw_angular_velocity_G{Eigen::Vector3d::Zero()}; // 经过限幅 / 加速度 / 滤波后的线速度 - Eigen::Vector3d linear_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d linear_velocity_G{Eigen::Vector3d::Zero()}; // 经过限幅 / 加速度 / 滤波后的角速度 - Eigen::Vector3d angular_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d angular_velocity_G{Eigen::Vector3d::Zero()}; // 可直接取出的 CartesianVelocity。 // @@ -111,7 +102,6 @@ public: bool position_reached{false}; bool orientation_reached{false}; bool reached{false}; - bool valid{false}; }; @@ -123,8 +113,7 @@ public: * * @param T_G_P_des TCP(P) 相对于 ScreenTag(G) 的目标位姿。 */ - bool setTargetPose( - const Eigen::Matrix4d& T_G_P_des); + bool setTargetPose(const Eigen::Matrix4d& T_G_P_des); /** * @brief 使用目标位置 + 目标姿态设置期望位姿。 @@ -136,16 +125,12 @@ public: /** * @brief 当前是否已经设置有效目标。 */ - bool hasTarget() const { - return target_valid_; - } + bool hasTarget() const { return target_valid_; } /** * @brief 获取目标位姿。 */ - const Eigen::Matrix4d& targetPose() const { - return T_G_P_des_; - } + const Eigen::Matrix4d& targetPose() const { return T_G_P_des_; } /** * @brief 根据当前 TCP 位姿计算 PBVS 速度命令。 @@ -176,16 +161,14 @@ public: * * x/y/z 分别控制。 */ - void setPositionGain( - const Eigen::Vector3d& kp); + void setPositionGain(const Eigen::Vector3d& kp); /** * @brief 设置姿态比例增益。 * * rx/ry/rz 分别控制。 */ - void setRotationGain( - const Eigen::Vector3d& kr); + void setRotationGain(const Eigen::Vector3d& kr); /** * @brief 设置六维速度上限。 @@ -195,8 +178,7 @@ public: * 前三维 m/s; * 后三维 rad/s。 */ - void setVelocityLimit6( - const std::array& vmax6); + void setVelocityLimit6(const std::array& vmax6); /** * @brief 设置六维加速度限制。 @@ -206,8 +188,7 @@ public: * * <= 0 表示对应维度不限制。 */ - void setAccelerationLimit6( - const std::array& amax6); + void setAccelerationLimit6(const std::array& amax6); /** * @brief 设置六维误差阈值。 @@ -217,21 +198,16 @@ public: * 前三维 m; * 后三维 rad。 */ - void setTolerance6( - const std::array& tolerance6); + void setTolerance6(const std::array& tolerance6); /** * @brief 设置一阶低通 alpha。 * - * alpha = 1: - * 不滤波。 + * alpha = 1:不滤波。 * * 0 < alpha < 1: * - * cmd = - * alpha * current - * + - * (1-alpha) * previous + * cmd = alpha * current + (1 - alpha) * previous */ void setTwistFilterAlpha(double alpha); @@ -244,8 +220,7 @@ public: * * enabled[5] = false; */ - void setAxisEnabled( - const std::array& enabled); + void setAxisEnabled(const std::array& enabled); /** * @brief 清空速度历史,但保留目标。 @@ -257,70 +232,42 @@ public: */ void reset(); - ComputeStatus lastComputeStatus() const { - return last_compute_status_; - } + ComputeStatus lastComputeStatus() const { return last_compute_status_; } - static const char* statusToString( - ComputeStatus status); + static const char* statusToString(ComputeStatus status); - const Eigen::Vector3d& lastPositionError() const { - return last_position_error_G_; - } + const Eigen::Vector3d& lastPositionError() const { return last_position_error_G_; } + const Eigen::Vector3d& lastRotationError() const { return last_rotation_error_G_; } - const Eigen::Vector3d& lastRotationError() const { - return last_rotation_error_G_; - } + const Eigen::Vector3d& positionGain() const { return kp_position_; } + const Eigen::Vector3d& rotationGain() const { return kp_rotation_; } - const Eigen::Vector3d& positionGain() const { - return kp_position_; - } + const std::array& velocityLimit6() const { return vmax6_; } + const std::array& accelerationLimit6() const { return amax6_; } + const std::array& tolerance6() const { return tolerance6_; } - const Eigen::Vector3d& rotationGain() const { - return kp_rotation_; - } + double twistFilterAlpha() const { return twist_lpf_alpha_; } - const std::array& velocityLimit6() const { - return vmax6_; - } - - const std::array& accelerationLimit6() const { - return amax6_; - } - - const std::array& tolerance6() const { - return tolerance6_; - } - - double twistFilterAlpha() const { - return twist_lpf_alpha_; - } - - const Eigen::Matrix& - lastTwistCommandG() const { + const Eigen::Matrix& lastTwistCommandG() const + { return last_twist_cmd_G_; } - bool lastReached() const { - return last_reached_; - } + bool lastReached() const { return last_reached_; } private: - static bool isFiniteTransform( - const Eigen::Matrix4d& T); + static bool isFiniteTransform(const Eigen::Matrix4d& T); static bool hasValidBottomRow( const Eigen::Matrix4d& T, double tolerance = 1e-6); - static bool isValidTransform( - const Eigen::Matrix4d& T); + static bool isValidTransform(const Eigen::Matrix4d& T); /** * @brief 将可能有微小数值误差的旋转矩阵投影到 SO(3)。 */ - static Eigen::Matrix3d projectToSO3( - const Eigen::Matrix3d& R); + static Eigen::Matrix3d projectToSO3(const Eigen::Matrix3d& R); /** * @brief 计算空间旋转误差,在 G frame 表达。 @@ -333,43 +280,27 @@ private: const Eigen::Matrix3d& R_des, const Eigen::Matrix3d& R_cur); - static double clampValue( - double value, - double lower, - double upper); + static double clampValue(double value, double lower, double upper); - static device::CartesianVelocity - toCartesianVelocity( + static device::CartesianVelocity toCartesianVelocity( const Eigen::Matrix& twist); private: // ---------------- target ---------------- - Eigen::Matrix4d T_G_P_des_{ - Eigen::Matrix4d::Identity() - }; - + Eigen::Matrix4d T_G_P_des_{Eigen::Matrix4d::Identity()}; bool target_valid_{false}; // ---------------- gains ---------------- - Eigen::Vector3d kp_position_{ - 2.0, - 2.0, - 1.5 - }; - - Eigen::Vector3d kp_rotation_{ - 1.5, - 1.5, - 1.5 - }; + Eigen::Vector3d kp_position_{2.0, 2.0, 1.5}; + Eigen::Vector3d kp_rotation_{1.5, 1.5, 1.5}; // ---------------- velocity limits ---------------- - // // [vx vy vz wx wy wz] // + std::array vmax6_{{ 0.10, 0.10, @@ -393,13 +324,12 @@ private: // ---------------- tolerance ---------------- std::array tolerance6_{{ - 0.0015, // x 1.5 mm - 0.0015, // y 1.5 mm - 0.0020, // z 2.0 mm - - 0.05, // rx ~2.9 deg - 0.05, // ry - 0.05 // rz + 0.0015, // x 1.5 mm + 0.0015, // y 1.5 mm + 0.0020, // z 2.0 mm + 0.05, // rx ~2.9 deg + 0.05, // ry + 0.05 // rz }}; // ---------------- axis enable ---------------- @@ -419,33 +349,24 @@ private: // ---------------- command history ---------------- - Eigen::Matrix - previous_twist_cmd_G_{ - Eigen::Matrix::Zero() - }; + Eigen::Matrix previous_twist_cmd_G_{ + Eigen::Matrix::Zero() + }; bool has_previous_twist_{false}; // ---------------- last output ---------------- - Eigen::Vector3d last_position_error_G_{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d last_position_error_G_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d last_rotation_error_G_{Eigen::Vector3d::Zero()}; - Eigen::Vector3d last_rotation_error_G_{ - Eigen::Vector3d::Zero() + Eigen::Matrix last_twist_cmd_G_{ + Eigen::Matrix::Zero() }; - Eigen::Matrix - last_twist_cmd_G_{ - Eigen::Matrix::Zero() - }; - bool last_reached_{false}; - ComputeStatus last_compute_status_{ - ComputeStatus::TARGET_NOT_SET - }; + ComputeStatus last_compute_status_{ComputeStatus::TARGET_NOT_SET}; }; } // namespace cmvr diff --git a/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp b/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp index fedd1f87..f83cc787 100644 --- a/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp +++ b/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp @@ -6,597 +6,478 @@ #include #include -namespace cmvr { - -PbvsController::PbvsController() +namespace cmvr { - resetTwistCommandState(); -} - -bool PbvsController::setTargetPose( - const Eigen::Matrix4d& T_G_P_des) -{ - if (!isValidTransform(T_G_P_des)) { - target_valid_ = false; - last_compute_status_ = - ComputeStatus::INVALID_TARGET; - return false; + PbvsController::PbvsController() + { + resetTwistCommandState(); } - T_G_P_des_ = T_G_P_des; - - // - // 视觉位姿可能有微小数值误差。 - // 强制把 rotation 投影到 SO(3)。 - // - T_G_P_des_.block<3, 3>(0, 0) = - projectToSO3( - T_G_P_des.block<3, 3>(0, 0)); - - target_valid_ = true; - last_compute_status_ = - ComputeStatus::OK; - - return true; -} - -bool PbvsController::setTargetPose( - const Eigen::Vector3d& position_G, - const Eigen::Matrix3d& rotation_G_P) -{ - if (!position_G.allFinite() || - !rotation_G_P.allFinite()) { - - target_valid_ = false; - last_compute_status_ = - ComputeStatus::INVALID_TARGET; - - return false; - } - - Eigen::Matrix4d T = - Eigen::Matrix4d::Identity(); - - T.block<3, 3>(0, 0) = - projectToSO3(rotation_G_P); - - T.block<3, 1>(0, 3) = - position_G; - - return setTargetPose(T); -} - -bool PbvsController::compute( - const Eigen::Matrix4d& T_G_P_cur, - const double dt, - Output& output) -{ - output = Output{}; - - last_reached_ = false; - last_position_error_G_.setZero(); - last_rotation_error_G_.setZero(); - last_twist_cmd_G_.setZero(); - - if (!target_valid_) { - last_compute_status_ = - ComputeStatus::TARGET_NOT_SET; - - return false; - } - - if (!std::isfinite(dt) || - dt <= 0.0) { - - last_compute_status_ = - ComputeStatus::INVALID_DT; - - return false; - } - - if (!isValidTransform(T_G_P_cur)) { - last_compute_status_ = - ComputeStatus::INVALID_CURRENT_POSE; - - return false; - } - - // ===================================================== - // 1. Current pose - // ===================================================== - - const Eigen::Vector3d p_cur_G = - T_G_P_cur.block<3, 1>(0, 3); - - const Eigen::Matrix3d R_cur_G_P = - projectToSO3( - T_G_P_cur.block<3, 3>(0, 0)); - - // ===================================================== - // 2. Desired pose - // ===================================================== - - const Eigen::Vector3d p_des_G = - T_G_P_des_.block<3, 1>(0, 3); - - const Eigen::Matrix3d R_des_G_P = - T_G_P_des_.block<3, 3>(0, 0); - - // ===================================================== - // 3. Position error - // - // e_p = p_des - p_cur - // - // expressed in G frame. - // ===================================================== - - Eigen::Vector3d e_pos_G = - p_des_G - - p_cur_G; - - // ===================================================== - // 4. Rotation error - // - // R_err = - // R_des * R_cur^T - // - // e_R = - // Log(R_err)^vee - // - // e_R is also expressed in G frame. - // ===================================================== - - Eigen::Vector3d e_rot_G = - rotationError( - R_des_G_P, - R_cur_G_P); - - if (!e_pos_G.allFinite() || - !e_rot_G.allFinite()) { - - last_compute_status_ = - ComputeStatus::INVALID_INPUT; - - return false; - } - - // ===================================================== - // 5. Disabled axes - // ===================================================== - - for (int i = 0; i < 3; ++i) { - if (!axis_enabled_[i]) { - e_pos_G[i] = 0.0; + bool PbvsController::setTargetPose(const Eigen::Matrix4d& T_G_P_des) + { + if (!isValidTransform(T_G_P_des)) + { + target_valid_ = false; + last_compute_status_ = ComputeStatus::INVALID_TARGET; + return false; } - if (!axis_enabled_[i + 3]) { - e_rot_G[i] = 0.0; - } - } + T_G_P_des_ = T_G_P_des; - last_position_error_G_ = - e_pos_G; + // + // 视觉位姿可能有微小数值误差。 + // 强制把 rotation 投影到 SO(3)。 + // + T_G_P_des_.block<3, 3>(0, 0) = projectToSO3(T_G_P_des.block<3, 3>(0, 0)); - last_rotation_error_G_ = - e_rot_G; - - output.position_error_G = - e_pos_G; - - output.rotation_error_G = - e_rot_G; - - // ===================================================== - // 6. Reached check - // ===================================================== - - bool position_reached = true; - bool orientation_reached = true; - - for (int i = 0; i < 3; ++i) { - - if (axis_enabled_[i] && - std::abs(e_pos_G[i]) > - tolerance6_[i]) { - - position_reached = false; - } - - if (axis_enabled_[i + 3] && - std::abs(e_rot_G[i]) > - tolerance6_[i + 3]) { - - orientation_reached = false; - } - } - - const bool reached = - position_reached && - orientation_reached; - - output.position_reached = - position_reached; - - output.orientation_reached = - orientation_reached; - - output.reached = - reached; - - last_reached_ = - reached; - - // ===================================================== - // 7. PBVS P control - // - // v = Kp * e_pos - // - // w = Kr * e_rot - // ===================================================== - - Eigen::Matrix - twist_raw_G = - Eigen::Matrix::Zero(); - - twist_raw_G.head<3>() = - kp_position_.cwiseProduct( - e_pos_G); - - twist_raw_G.tail<3>() = - kp_rotation_.cwiseProduct( - e_rot_G); - - // ===================================================== - // 8. Dead zone - // - // 某个轴已经进入误差阈值,则这个轴不再主动运动。 - // ===================================================== - - for (int i = 0; i < 6; ++i) { - - if (!axis_enabled_[i]) { - twist_raw_G[i] = 0.0; - continue; - } - - const double error_value = - i < 3 - ? e_pos_G[i] - : e_rot_G[i - 3]; - - if (std::abs(error_value) <= - tolerance6_[i]) { - - twist_raw_G[i] = 0.0; - } - } - - output.raw_linear_velocity_G = - twist_raw_G.head<3>(); - - output.raw_angular_velocity_G = - twist_raw_G.tail<3>(); - - // ===================================================== - // 9. Velocity limits - // ===================================================== - - Eigen::Matrix - twist_vel_limited = - twist_raw_G; - - for (int i = 0; i < 6; ++i) { - - const double vmax = - vmax6_[i]; - - if (!std::isfinite(vmax) || - vmax <= 0.0) { - - twist_vel_limited[i] = 0.0; - continue; - } - - twist_vel_limited[i] = - clampValue( - twist_vel_limited[i], - -vmax, - vmax); - } - - // ===================================================== - // 10. Reached: - // - // 进入完整目标阈值后直接输出 0。 - // - // 上层可以随后调用 RobotArm::stopL()。 - // ===================================================== - - if (reached) { - - previous_twist_cmd_G_.setZero(); - has_previous_twist_ = true; - - last_twist_cmd_G_.setZero(); - - output.linear_velocity_G.setZero(); - output.angular_velocity_G.setZero(); - - output.twist_G = - device::CartesianVelocity{}; - - output.valid = true; - - last_compute_status_ = - ComputeStatus::OK; + target_valid_ = true; + last_compute_status_ = ComputeStatus::OK; return true; } - // ===================================================== - // 11. Acceleration limits - // ===================================================== + bool PbvsController::setTargetPose(const Eigen::Vector3d& position_G, const Eigen::Matrix3d& rotation_G_P) + { + if (!position_G.allFinite() || !rotation_G_P.allFinite()) + { + target_valid_ = false; + last_compute_status_ = ComputeStatus::INVALID_TARGET; - Eigen::Matrix - twist_acc_limited; + return false; + } - if (!has_previous_twist_) { + Eigen::Matrix4d T = Eigen::Matrix4d::Identity(); + T.block<3, 3>(0, 0) = projectToSO3(rotation_G_P); + + T.block<3, 1>(0, 3) = position_G; + + return setTargetPose(T); + } + + bool PbvsController::compute(const Eigen::Matrix4d& T_G_P_cur, const double dt, Output& output) + { + output = Output{}; + + last_reached_ = false; + last_position_error_G_.setZero(); + last_rotation_error_G_.setZero(); + last_twist_cmd_G_.setZero(); + + if (!target_valid_) + { + last_compute_status_ = ComputeStatus::TARGET_NOT_SET; + + return false; + } + + if (!std::isfinite(dt) || dt <= 0.0) + { + last_compute_status_ = ComputeStatus::INVALID_DT; + + return false; + } + + if (!isValidTransform(T_G_P_cur)) + { + last_compute_status_ = ComputeStatus::INVALID_CURRENT_POSE; + + return false; + } + + // ===================================================== + // 1. Current pose + // ===================================================== + + const Eigen::Vector3d p_cur_G = T_G_P_cur.block<3, 1>(0, 3); + + const Eigen::Matrix3d R_cur_G_P = projectToSO3(T_G_P_cur.block<3, 3>(0, 0)); + + // ===================================================== + // 2. Desired pose + // ===================================================== + + const Eigen::Vector3d p_des_G = T_G_P_des_.block<3, 1>(0, 3); + + const Eigen::Matrix3d R_des_G_P = T_G_P_des_.block<3, 3>(0, 0); + + // ===================================================== + // 3. Position error + // + // e_p = p_des - p_cur + // + // expressed in G frame. + // ===================================================== + + Eigen::Vector3d e_pos_G = p_des_G - p_cur_G; + + // ===================================================== + // 4. Rotation error + // + // R_err = + // R_des * R_cur^T + // + // e_R = + // Log(R_err)^vee + // + // e_R is also expressed in G frame. + // ===================================================== + + Eigen::Vector3d e_rot_G = rotationError(R_des_G_P, R_cur_G_P); + + if (!e_pos_G.allFinite() || !e_rot_G.allFinite()) + { + last_compute_status_ = ComputeStatus::INVALID_INPUT; + + return false; + } + + // ===================================================== + // 5. Disabled axes + // ===================================================== + + for (int i = 0; i < 3; ++i) + { + if (!axis_enabled_[i]) + { + e_pos_G[i] = 0.0; + } + + if (!axis_enabled_[i + 3]) + { + e_rot_G[i] = 0.0; + } + } + + last_position_error_G_ = e_pos_G; + + last_rotation_error_G_ = e_rot_G; + + output.position_error_G = e_pos_G; + + output.rotation_error_G = e_rot_G; + + // ===================================================== + // 6. Reached check + // ===================================================== + + bool position_reached = true; + bool orientation_reached = true; + + for (int i = 0; i < 3; ++i) + { + if (axis_enabled_[i] && std::abs(e_pos_G[i]) > tolerance6_[i]) + { + position_reached = false; + } + + if (axis_enabled_[i + 3] && std::abs(e_rot_G[i]) > tolerance6_[i + 3]) + { + orientation_reached = false; + } + } + + const bool reached = position_reached && orientation_reached; + + output.position_reached = position_reached; + + output.orientation_reached = orientation_reached; + + output.reached = reached; + + last_reached_ = reached; + + // ===================================================== + // 7. PBVS P control + // + // v = Kp * e_pos + // + // w = Kr * e_rot + // ===================================================== + + Eigen::Matrix twist_raw_G = Eigen::Matrix::Zero(); + + twist_raw_G.head<3>() = kp_position_.cwiseProduct(e_pos_G); + + twist_raw_G.tail<3>() = kp_rotation_.cwiseProduct(e_rot_G); + + // ===================================================== + // 8. Dead zone + // + // 某个轴已经进入误差阈值,则这个轴不再主动运动。 + // ===================================================== + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_raw_G[i] = 0.0; + continue; + } + + const double error_value = i < 3 ? e_pos_G[i] : e_rot_G[i - 3]; + + if (std::abs(error_value) <= tolerance6_[i]) + { + twist_raw_G[i] = 0.0; + } + } + + output.raw_linear_velocity_G = twist_raw_G.head<3>(); + + output.raw_angular_velocity_G = twist_raw_G.tail<3>(); + + // ===================================================== + // 9. Velocity limits + // ===================================================== + + Eigen::Matrix twist_vel_limited = twist_raw_G; + + for (int i = 0; i < 6; ++i) + { + const double vmax = vmax6_[i]; + + if (!std::isfinite(vmax) || vmax <= 0.0) + { + twist_vel_limited[i] = 0.0; + continue; + } + + twist_vel_limited[i] = clampValue(twist_vel_limited[i], -vmax, vmax); + } + + // ===================================================== + // 10. Reached: + // + // 进入完整目标阈值后直接输出 0。 + // + // 上层可以随后调用 RobotArm::stopL()。 + // ===================================================== + + if (reached) + { + previous_twist_cmd_G_.setZero(); + has_previous_twist_ = true; + + last_twist_cmd_G_.setZero(); + + output.linear_velocity_G.setZero(); + output.angular_velocity_G.setZero(); + + output.twist_G = device::CartesianVelocity{}; + + output.valid = true; + + last_compute_status_ = ComputeStatus::OK; + + return true; + } + + // ===================================================== + // 11. Acceleration limits + // ===================================================== + + Eigen::Matrix twist_acc_limited; + + if (!has_previous_twist_) + { + previous_twist_cmd_G_.setZero(); + has_previous_twist_ = true; + } + + twist_acc_limited = previous_twist_cmd_G_; + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_acc_limited[i] = 0.0; + continue; + } + + const double amax = amax6_[i]; + + // <=0:不做加速度限制 + if (!std::isfinite(amax) || amax <= 0.0) + { + twist_acc_limited[i] = twist_vel_limited[i]; + + continue; + } + + const double dv_max = amax * dt; + + const double dv_des = twist_vel_limited[i] - previous_twist_cmd_G_[i]; + + const double dv = clampValue(dv_des, -dv_max, dv_max); + + twist_acc_limited[i] = previous_twist_cmd_G_[i] + dv; + } + + // ===================================================== + // 12. First-order LPF + // ===================================================== + + Eigen::Matrix twist_filtered = twist_acc_limited; + + const double alpha = std::clamp(twist_lpf_alpha_, 0.0, 1.0); + + if (alpha > 0.0 && alpha < 1.0) + { + twist_filtered = alpha * twist_acc_limited + (1.0 - alpha) * previous_twist_cmd_G_; + } + + // ===================================================== + // 13. Make sure disabled axis is zero + // ===================================================== + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_filtered[i] = 0.0; + } + } + + // ===================================================== + // 14. Save state + // ===================================================== + + previous_twist_cmd_G_ = twist_filtered; + + last_twist_cmd_G_ = twist_filtered; + + // ===================================================== + // 15. Output + // ===================================================== + + output.linear_velocity_G = twist_filtered.head<3>(); + + output.angular_velocity_G = twist_filtered.tail<3>(); + + output.twist_G = toCartesianVelocity(twist_filtered); + + output.valid = true; + + last_compute_status_ = ComputeStatus::OK; + + return true; + } + + bool PbvsController::compute(const Eigen::Matrix4d& T_G_P_cur, const double dt, device::CartesianVelocity& twist_G_out) + { + Output output; + + if (!compute(T_G_P_cur, dt, output)) + { + twist_G_out = device::CartesianVelocity{}; + + return false; + } + + twist_G_out = output.twist_G; + + return true; + } + + void PbvsController::setPositionGain(const Eigen::Vector3d& kp) + { + for (int i = 0; i < 3; ++i) + { + if (std::isfinite(kp[i]) && kp[i] >= 0.0) + { + kp_position_[i] = kp[i]; + } + } + } + + void PbvsController::setRotationGain(const Eigen::Vector3d& kr) + { + for (int i = 0; i < 3; ++i) + { + if (std::isfinite(kr[i]) && kr[i] >= 0.0) + { + kp_rotation_[i] = kr[i]; + } + } + } + + void PbvsController::setVelocityLimit6(const std::array& vmax6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(vmax6[i]) && vmax6[i] >= 0.0) + { + vmax6_[i] = vmax6[i]; + } + } + } + + void PbvsController::setAccelerationLimit6(const std::array& amax6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(amax6[i])) + { + amax6_[i] = amax6[i]; + } + } + } + + void PbvsController::setTolerance6(const std::array& tolerance6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(tolerance6[i]) && tolerance6[i] >= 0.0) + { + tolerance6_[i] = tolerance6[i]; + } + } + } + + void PbvsController::setTwistFilterAlpha(const double alpha) + { + if (!std::isfinite(alpha)) + { + return; + } + + twist_lpf_alpha_ = std::clamp(alpha, 0.0, 1.0); + } + + void PbvsController::setAxisEnabled(const std::array& enabled) + { + axis_enabled_ = enabled; + } + + void PbvsController::resetTwistCommandState() + { previous_twist_cmd_G_.setZero(); - has_previous_twist_ = true; + last_twist_cmd_G_.setZero(); + + has_previous_twist_ = false; } - twist_acc_limited = - previous_twist_cmd_G_; + void PbvsController::reset() + { + T_G_P_des_.setIdentity(); - for (int i = 0; i < 6; ++i) { + target_valid_ = false; - if (!axis_enabled_[i]) { - twist_acc_limited[i] = 0.0; - continue; - } + last_position_error_G_.setZero(); + last_rotation_error_G_.setZero(); - const double amax = - amax6_[i]; + last_reached_ = false; - // <=0:不做加速度限制 - if (!std::isfinite(amax) || - amax <= 0.0) { + resetTwistCommandState(); - twist_acc_limited[i] = - twist_vel_limited[i]; - - continue; - } - - const double dv_max = - amax * dt; - - const double dv_des = - twist_vel_limited[i] - - - previous_twist_cmd_G_[i]; - - const double dv = - clampValue( - dv_des, - -dv_max, - dv_max); - - twist_acc_limited[i] = - previous_twist_cmd_G_[i] - + - dv; + last_compute_status_ = ComputeStatus::TARGET_NOT_SET; } - // ===================================================== - // 12. First-order LPF - // ===================================================== - - Eigen::Matrix - twist_filtered = - twist_acc_limited; - - const double alpha = - std::clamp( - twist_lpf_alpha_, - 0.0, - 1.0); - - if (alpha > 0.0 && - alpha < 1.0) { - - twist_filtered = - alpha * - twist_acc_limited - + - (1.0 - alpha) * - previous_twist_cmd_G_; - } - - // ===================================================== - // 13. Make sure disabled axis is zero - // ===================================================== - - for (int i = 0; i < 6; ++i) { - if (!axis_enabled_[i]) { - twist_filtered[i] = 0.0; - } - } - - // ===================================================== - // 14. Save state - // ===================================================== - - previous_twist_cmd_G_ = - twist_filtered; - - last_twist_cmd_G_ = - twist_filtered; - - // ===================================================== - // 15. Output - // ===================================================== - - output.linear_velocity_G = - twist_filtered.head<3>(); - - output.angular_velocity_G = - twist_filtered.tail<3>(); - - output.twist_G = - toCartesianVelocity( - twist_filtered); - - output.valid = true; - - last_compute_status_ = - ComputeStatus::OK; - - return true; -} - -bool PbvsController::compute( - const Eigen::Matrix4d& T_G_P_cur, - const double dt, - device::CartesianVelocity& twist_G_out) -{ - Output output; - - if (!compute( - T_G_P_cur, - dt, - output)) { - - twist_G_out = - device::CartesianVelocity{}; - - return false; - } - - twist_G_out = - output.twist_G; - - return true; -} - -void PbvsController::setPositionGain( - const Eigen::Vector3d& kp) -{ - for (int i = 0; i < 3; ++i) { - if (std::isfinite(kp[i]) && - kp[i] >= 0.0) { - - kp_position_[i] = - kp[i]; - } - } -} - -void PbvsController::setRotationGain( - const Eigen::Vector3d& kr) -{ - for (int i = 0; i < 3; ++i) { - if (std::isfinite(kr[i]) && - kr[i] >= 0.0) { - - kp_rotation_[i] = - kr[i]; - } - } -} - -void PbvsController::setVelocityLimit6( - const std::array& vmax6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(vmax6[i]) && - vmax6[i] >= 0.0) { - - vmax6_[i] = - vmax6[i]; - } - } -} - -void PbvsController::setAccelerationLimit6( - const std::array& amax6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(amax6[i])) { - amax6_[i] = - amax6[i]; - } - } -} - -void PbvsController::setTolerance6( - const std::array& tolerance6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(tolerance6[i]) && - tolerance6[i] >= 0.0) { - - tolerance6_[i] = - tolerance6[i]; - } - } -} - -void PbvsController::setTwistFilterAlpha( - const double alpha) -{ - if (!std::isfinite(alpha)) { - return; - } - - twist_lpf_alpha_ = - std::clamp( - alpha, - 0.0, - 1.0); -} - -void PbvsController::setAxisEnabled( - const std::array& enabled) -{ - axis_enabled_ = - enabled; -} - -void PbvsController::resetTwistCommandState() -{ - previous_twist_cmd_G_.setZero(); - last_twist_cmd_G_.setZero(); - - has_previous_twist_ = false; -} - -void PbvsController::reset() -{ - T_G_P_des_.setIdentity(); - - target_valid_ = false; - - last_position_error_G_.setZero(); - last_rotation_error_G_.setZero(); - - last_reached_ = false; - - resetTwistCommandState(); - - last_compute_status_ = - ComputeStatus::TARGET_NOT_SET; -} - -const char* PbvsController::statusToString( - const ComputeStatus status) -{ - switch (status) { - + const char* PbvsController::statusToString(const ComputeStatus status) + { + switch (status) + { case ComputeStatus::OK: return "ok"; @@ -617,158 +498,121 @@ const char* PbvsController::statusToString( default: return "unknown"; - } -} - -bool PbvsController::isFiniteTransform( - const Eigen::Matrix4d& T) -{ - return T.allFinite(); -} - -bool PbvsController::hasValidBottomRow( - const Eigen::Matrix4d& T, - const double tolerance) -{ - return - std::abs(T(3, 0)) <= tolerance && - std::abs(T(3, 1)) <= tolerance && - std::abs(T(3, 2)) <= tolerance && - std::abs(T(3, 3) - 1.0) <= tolerance; -} - -bool PbvsController::isValidTransform( - const Eigen::Matrix4d& T) -{ - if (!isFiniteTransform(T)) { - return false; + } } - if (!hasValidBottomRow(T)) { - return false; + bool PbvsController::isFiniteTransform(const Eigen::Matrix4d& T) + { + return T.allFinite(); } - return true; -} - -Eigen::Matrix3d PbvsController::projectToSO3( - const Eigen::Matrix3d& R) -{ - if (!R.allFinite()) { - return Eigen::Matrix3d::Identity(); + bool PbvsController::hasValidBottomRow(const Eigen::Matrix4d& T, const double tolerance) + { + return std::abs(T(3, 0)) <= tolerance && std::abs(T(3, 1)) <= tolerance && + std::abs(T(3, 2)) <= tolerance && std::abs(T(3, 3) - 1.0) <= tolerance; } - Eigen::JacobiSVD svd( - R, - Eigen::ComputeFullU | - Eigen::ComputeFullV); + bool PbvsController::isValidTransform(const Eigen::Matrix4d& T) + { + if (!isFiniteTransform(T)) + { + return false; + } - Eigen::Matrix3d U = - svd.matrixU(); + if (!hasValidBottomRow(T)) + { + return false; + } - const Eigen::Matrix3d V = - svd.matrixV(); - - Eigen::Matrix3d R_projected = - U * V.transpose(); - - // - // 确保 det = +1,而不是 reflection。 - // - if (R_projected.determinant() < 0.0) { - - U.col(2) *= -1.0; - - R_projected = - U * V.transpose(); + return true; } - return R_projected; -} + Eigen::Matrix3d PbvsController::projectToSO3(const Eigen::Matrix3d& R) + { + if (!R.allFinite()) + { + return Eigen::Matrix3d::Identity(); + } -Eigen::Vector3d PbvsController::rotationError( - const Eigen::Matrix3d& R_des, - const Eigen::Matrix3d& R_cur) -{ - const Eigen::Matrix3d R_d = - projectToSO3(R_des); + Eigen::JacobiSVD svd(R, Eigen::ComputeFullU | Eigen::ComputeFullV); - const Eigen::Matrix3d R_c = - projectToSO3(R_cur); + Eigen::Matrix3d U = svd.matrixU(); - // - // 空间旋转误差,在 G frame 表达。 - // - // 当前为 I,目标绕 +Z 旋转 theta: - // - // R_err = R_des - // - // 得到 +theta Z, - // 因此角速度方向正确。 - // - const Eigen::Matrix3d R_err = - R_d * - R_c.transpose(); + const Eigen::Matrix3d V = svd.matrixV(); - Eigen::AngleAxisd aa( - R_err); + Eigen::Matrix3d R_projected = U * V.transpose(); - const double angle = - aa.angle(); + // + // 确保 det = +1,而不是 reflection。 + // + if (R_projected.determinant() < 0.0) + { + U.col(2) *= -1.0; - if (!std::isfinite(angle) || - std::abs(angle) <= 1e-12) { + R_projected = U * V.transpose(); + } - return Eigen::Vector3d::Zero(); + return R_projected; } - const Eigen::Vector3d axis = - aa.axis(); + Eigen::Vector3d PbvsController::rotationError(const Eigen::Matrix3d& R_des, const Eigen::Matrix3d& R_cur) + { + const Eigen::Matrix3d R_d = projectToSO3(R_des); - if (!axis.allFinite()) { - return Eigen::Vector3d::Zero(); + const Eigen::Matrix3d R_c = projectToSO3(R_cur); + + // + // 空间旋转误差,在 G frame 表达。 + // + // 当前为 I,目标绕 +Z 旋转 theta: + // + // R_err = R_des + // + // 得到 +theta Z, + // 因此角速度方向正确。 + // + const Eigen::Matrix3d R_err = R_d * R_c.transpose(); + + Eigen::AngleAxisd aa(R_err); + + const double angle = aa.angle(); + + if (!std::isfinite(angle) || std::abs(angle) <= 1e-12) + { + return Eigen::Vector3d::Zero(); + } + + const Eigen::Vector3d axis = aa.axis(); + + if (!axis.allFinite()) + { + return Eigen::Vector3d::Zero(); + } + + return axis * angle; } - return axis * angle; -} + double PbvsController::clampValue(const double value, const double lower, const double upper) + { + return std::max(lower, std::min(value, upper)); + } -double PbvsController::clampValue( - const double value, - const double lower, - const double upper) -{ - return std::max( - lower, - std::min( - value, - upper)); -} + device::CartesianVelocity PbvsController::toCartesianVelocity(const Eigen::Matrix& twist) + { + device::CartesianVelocity velocity; -device::CartesianVelocity -PbvsController::toCartesianVelocity( - const Eigen::Matrix& twist) -{ - device::CartesianVelocity velocity; + velocity.vx = twist[0]; - velocity.vx = - twist[0]; + velocity.vy = twist[1]; - velocity.vy = - twist[1]; + velocity.vz = twist[2]; - velocity.vz = - twist[2]; + velocity.wx = twist[3]; - velocity.wx = - twist[3]; + velocity.wy = twist[4]; - velocity.wy = - twist[4]; + velocity.wz = twist[5]; - velocity.wz = - twist[5]; - - return velocity; -} - -} // namespace cmvr \ No newline at end of file + return velocity; + } +} // 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..34e6bd89 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 @@ -6,15 +6,14 @@ #include -#include +#include "environment/include/robot_model.h" namespace cmvr { /** - * @brief 基于 Pinocchio 的 URDF 解析工具类。 + * @brief 从已加载的 RobotModel 提取运动链信息。 * * 主要职责: - * - 加载 URDF 到 Pinocchio 模型 * - 提取 base->tip 链路信息 * - 输出链路 q/v 索引范围、关节顺序、位置/速度限位 */ @@ -64,39 +63,24 @@ 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_; } - -private: - pinocchio::Model model_; - bool loaded_{false}; + 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); }; } // 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/motion_planner/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/CMakeLists.txt deleted file mode 100644 index aadc080e..00000000 --- a/cmvr-es/algorithms/motion_planner/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(base_motion) -add_subdirectory(arm_motion) diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt deleted file mode 100644 index f5313688..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -add_library(arm_motion SHARED - cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp - joint_motion/toppra/src/toppra_joint_motion_planner.cpp -) - -target_include_directories(arm_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(arm_motion - PUBLIC - cmvr_es::ik_solver - cmvr_es::base_motion -) - -add_library(cmvr_es::arm_motion ALIAS arm_motion) -add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion) -install(TARGETS arm_motion LIBRARY DESTINATION lib) - -add_executable(toppra_joint_motion_planner_test - joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp -) - -target_link_libraries(toppra_joint_motion_planner_test - PRIVATE - cmvr_es::algorithms::arm_motion - gtest - gtest_main -) - -add_executable(pinocchio_speedl_limits_test - cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp -) -target_compile_definitions(pinocchio_speedl_limits_test PRIVATE - CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}") -target_link_libraries(pinocchio_speedl_limits_test PRIVATE - cmvr_es::algorithms::arm_motion gtest gtest_main) diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h deleted file mode 100644 index 816854f0..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_H -#define CMVR_ES_CARTESIAN_MOTION_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; -}; - -class CartesianMotionPlanner { -public: - virtual ~CartesianMotionPlanner() = default; - - virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config, - std::size_t dof) = 0; - 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; - - virtual bool speedLStep(const CartesianVelocity& target_velocity, - double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - FrameType frame) = 0; - - virtual bool updateSpeedLAcceleration(double acceleration) = 0; - virtual bool updateSpeedLLimits(const SpeedLOptions& options) { - return !options.linear_jerk && !options.continuous_linear_reversal.value_or(false) && - updateSpeedLAcceleration(options.acceleration); - } - virtual bool captureSpeedLReference(const std::vector&, - const CartesianVelocity&, FrameType, SpeedLReference&) { return false; } - virtual CartesianVelocity getSpeedLCommandTwistBase() const = 0; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h deleted file mode 100644 index ec527c68..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h +++ /dev/null @@ -1,63 +0,0 @@ -#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/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "cmvr/config/arm_config/arm_config.pb.h" - -namespace cmvr::device { - -class CartesianMotionPlannerFactory { -public: - static std::shared_ptr create( - const config::MoveLConfig& move_l, - const config::SpeedLConfig& speed_l, - const std::shared_ptr& solver) - { - if (!solver) { - return nullptr; - } - switch (move_l.algorithm_case()) { - case config::MoveLConfig::kPinocchioCartesianMotionPlanner: - if (speed_l.algorithm_case() != - config::SpeedLConfig::kPinocchioCartesianMotionPlanner) { - return nullptr; - } - return std::make_shared(solver); - case config::MoveLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } - - static const config::SpeedLPlannerConfig* speedLConfig( - const config::SpeedLConfig& cfg) - { - switch (cfg.algorithm_case()) { - case config::SpeedLConfig::kPinocchioCartesianMotionPlanner: - return &cfg.pinocchio_cartesian_motion_planner(); - case config::SpeedLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } - - static const config::MoveLPlannerConfig* moveLConfig( - const config::MoveLConfig& cfg) - { - switch (cfg.algorithm_case()) { - case config::MoveLConfig::kPinocchioCartesianMotionPlanner: - return &cfg.pinocchio_cartesian_motion_planner(); - case config::MoveLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h deleted file mode 100644 index b83848dc..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H -#define CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H - -#include - -#include -#include - -#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" -#include "../../cartesian_motion_planner.h" -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" - -namespace cmvr::device { - -class PinocchioCartesianMotionPlanner final : public CartesianMotionPlanner { -public: - explicit PinocchioCartesianMotionPlanner(std::shared_ptr solver); - - bool configureSpeedL(const config::SpeedLPlannerConfig& config, - std::size_t dof) override; - 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; - - bool speedLStep(const CartesianVelocity& target_velocity, - double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - FrameType frame) override; - - bool updateSpeedLAcceleration(double acceleration) override; - bool updateSpeedLLimits(const SpeedLOptions& options) override; - bool captureSpeedLReference(const std::vector& q, const CartesianVelocity& target, - FrameType frame, SpeedLReference& reference) override; - CartesianVelocity getSpeedLCommandTwistBase() const override; - -private: - bool refreshJointAccelerationLimits_(); - Eigen::VectorXd applyJointAccelerationLimits_(const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - double dt) const; - 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; - bool updateAndValidateSpeedLLineDeviation_(const std::vector& q_measured, - bool is_stop_command, - const Eigen::Vector3d& command_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::MoveLPlannerConfig movel_config_{}; - config::SpeedLPlannerConfig speedl_config_{}; - cmvr::CartesianTwistLimiter twist_limiter_{}; - Eigen::VectorXd joint_acceleration_limits_; - std::vector prev_qdot_command_; - Eigen::Matrix speedl_command_twist_base_{Eigen::Matrix::Zero()}; - 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_deviation_warned_{false}; - bool speedl_line_direction_warned_{false}; - - // speedL 是否已经进入停止阶段。 - // 停止阶段不要每 1 ms 用 measured twist 重新点燃 Cartesian planner。 - bool speedl_stop_active_{false}; - - bool speedl_configured_{false}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp deleted file mode 100644 index 661b771a..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp +++ /dev/null @@ -1,1321 +0,0 @@ -#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h" -#include "algorithms/motion_planner/base_motion/motion_profile/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 - -PinocchioCartesianMotionPlanner::PinocchioCartesianMotionPlanner( - std::shared_ptr solver) - : solver_(std::move(solver)) -{ -} - -bool PinocchioCartesianMotionPlanner::refreshJointAccelerationLimits_() -{ - joint_acceleration_limits_.resize(0); - if (!solver_) { - return false; - } - const auto& limits = solver_->jointLimitPolicy().limits(); - if (limits.source() != config::JOINT_LIMIT_SOURCE_CUSTOM) { - 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; - } - } - - joint_acceleration_limits_.resize(static_cast(joint_names.size())); - for (Eigen::Index i = 0; i < joint_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) << "[PinocchioCartesianMotionPlanner] invalid custom qdd for " - << joint_name; - return false; - } - joint_acceleration_limits_[i] = std::abs(it->second.qdd()); - } - return true; -} - -Eigen::VectorXd PinocchioCartesianMotionPlanner::applyJointAccelerationLimits_( - const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - const double dt) const -{ - if (reference.size() != qdot.size() || dt <= 0.0) { - return qdot; - } - - Eigen::VectorXd limited = qdot; - for (Eigen::Index i = 0; i < qdot.size(); ++i) { - double acc_limit = 8.0; - if (joint_acceleration_limits_.size() == qdot.size() && - joint_acceleration_limits_[i] > 0.0) { - acc_limit = joint_acceleration_limits_[i]; - } - - const double delta_max = acc_limit * dt; - const double delta = clamp(qdot[i] - reference[i], -delta_max, delta_max); - limited[i] = reference[i] + delta; - } - return limited; -} - -bool PinocchioCartesianMotionPlanner::configureSpeedL(const config::SpeedLPlannerConfig& config, - const std::size_t dof) -{ - if (!solver_ || dof == 0) { - return false; - } - const auto solver_dof = static_cast(std::max(0, solver_->chainVelocityDof())); - if (solver_dof != 0 && solver_dof != dof) { - return false; - } - speedl_config_ = config; - - if (!refreshJointAccelerationLimits_()) { - return false; - } - - cartesian_motion::configureTwistLimiterFromSpeedLConfig(twist_limiter_, speedl_config_); - speedl_applied_linear_jerk_ = -1.0; - - prev_qdot_command_.assign(dof, 0.0); - speedl_command_twist_base_.setZero(); - speedl_line_check_active_ = false; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - speedl_stop_active_ = false; - speedl_applied_acceleration_ = positiveOr(speedl_config_.linear_acceleration_max(), 5.0); - speedl_applied_angular_acceleration_ = positiveOr(speedl_config_.angular_acceleration_max(), 5.0); - speedl_configured_ = true; - return true; -} - -bool PinocchioCartesianMotionPlanner::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 PinocchioCartesianMotionPlanner::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 << "[PinocchioCartesianMotionPlanner][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::SCurve curve(velocity, acceleration, jerk); - const cmvr::SCurveProfile profile = curve.calculateProfile(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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][moveL][plan] line direction deviation warning: deviation_deg=" - << deviation_deg << ", warn_deg=" << warn_deg - << ", traveled_m=" << traveled; - direction_warned = true; - } - return true; -} - -bool PinocchioCartesianMotionPlanner::updateAndValidateSpeedLLineDeviation_( - const std::vector& q_measured, - const bool is_stop_command, - const Eigen::Vector3d& command_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) { - speedl_line_check_active_ = false; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - return true; - } - - Eigen::Matrix4d tcp_pose_base = Eigen::Matrix4d::Identity(); - if (!solver_->fk(q_measured, tcp_pose_base, true)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line check FK failed"; - return false; - } - const Eigen::Vector3d tcp_position = tcp_pose_base.block<3, 1>(0, 3); - const Eigen::Vector3d command_direction = command_linear_base / command_norm; - - bool reset_line = !speedl_line_check_active_; - if (!reset_line && 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(speedl_line_direction_base_, command_direction); - reset_line = command_change_deg >= reset_deg; - } - - if (reset_line) { - speedl_line_start_tcp_base_ = tcp_position; - speedl_line_direction_base_ = command_direction; - speedl_line_check_active_ = true; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - return true; - } - - const Eigen::Vector3d delta = tcp_position - 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(speedl_line_start_tcp_base_, 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) << "[PinocchioCartesianMotionPlanner][speedL] line deviation too large: lateral_error_m=" - << lateral_error << ", stop_m=" << stop_m - << ", traveled_m=" << traveled; - return false; - } - - const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); - if (!speedl_line_deviation_warned_ && lateral_error >= warn_m) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][speedL] line deviation warning: lateral_error_m=" - << lateral_error << ", warn_m=" << warn_m - << ", traveled_m=" << traveled; - speedl_line_deviation_warned_ = true; - } - - const Eigen::Vector3d actual_direction = delta / traveled; - const double deviation_deg = - directionDeviationDeg(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) << "[PinocchioCartesianMotionPlanner][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 (!speedl_line_direction_warned_ && deviation_deg >= warn_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][speedL] line direction deviation warning: deviation_deg=" - << deviation_deg << ", warn_deg=" << warn_deg - << ", traveled_m=" << traveled; - speedl_line_direction_warned_ = true; - } - - return true; -} - -bool PinocchioCartesianMotionPlanner::speedLStep(const CartesianVelocity& target_velocity, - const double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - const FrameType frame) -{ - qd_command.clear(); - if (!solver_ || !speedl_configured_ || dt <= 0.0) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] invalid state: solver=" - << (solver_ ? 1 : 0) - << ", configured=" << (speedl_configured_ ? 1 : 0) - << ", dt=" << dt; - return false; - } - if (static_cast(q_measured.size()) != solver_->chainDof() || - static_cast(qd_measured.size()) != solver_->chainVelocityDof()) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] state size mismatch: q=" - << q_measured.size() << "/" << solver_->chainDof() - << ", qd=" << qd_measured.size() << "/" << solver_->chainVelocityDof(); - return false; - } - - Eigen::Matrix measured_twist_base = Eigen::Matrix::Zero(); - Eigen::MatrixXd jacobian_base; - Eigen::Matrix3d base_R_tool = Eigen::Matrix3d::Identity(); - if (!solver_->computeTwistBaseAtQ(q_measured, - qd_measured, - true, - measured_twist_base, - &jacobian_base, - &base_R_tool)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] computeTwistBaseAtQ failed"; - return false; - } - - const Eigen::Matrix target_twist = - common::math::velocityToVector(target_velocity); - - const bool is_stop_command = - target_twist.squaredNorm() <= 1e-12; - - if (is_stop_command) { - if (!speedl_stop_active_) { - // 只在 stop 边沿执行一次。 - // - // 非常重要: - // 不再调用 - // twist_limiter_.synchronize(measured_twist_base, dt, true); - // - // 停止应当从“上一拍已经发送出去的 command twist” - // 连续规划到 0,而不是每 1 ms 被 measured twist 重新点燃。 - speedl_stop_active_ = true; - - twist_limiter_.stop(); - } - } else { - // 收到新的非零 speedL,退出停止状态。 - speedl_stop_active_ = false; - - // 从静止开始一个新的 speedL command。 - if (speedl_command_twist_base_.squaredNorm() <= 1e-12 && - (!twist_limiter_.continuousLinearReversalEnabled() || !twist_limiter_.isMoving())) { - twist_limiter_.initialize( - Eigen::Matrix::Zero()); - } - - twist_limiter_.setTargetTwist( - target_twist, - common::math::toPlannerFrame(frame)); - } - - speedl_command_twist_base_ = - twist_limiter_.update(dt, base_R_tool); - if (!updateAndValidateSpeedLLineDeviation_(q_measured, - is_stop_command, - speedl_command_twist_base_.head<3>())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line deviation check failed"; - return false; - } - - Eigen::VectorXd reference = toEigenVector(qd_measured); - if (prev_qdot_command_.size() == q_measured.size()) { - reference = toEigenVector(prev_qdot_command_); - } - - const bool enforce_acceleration_limits = - !speedl_config_.has_enforce_joint_acceleration_limits() || - speedl_config_.enforce_joint_acceleration_limits(); - std::vector qdot_std; - if (!solver_->solveVelocityBase(jacobian_base, - speedl_command_twist_base_, - q_measured, - qdot_std, - std::numeric_limits::infinity())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] solveVelocityBase failed"; - return false; - } - Eigen::VectorXd qdot = toEigenVector(qdot_std); - if (enforce_acceleration_limits) { - qdot = applyJointAccelerationLimits_(qdot, reference, dt); - } - const Eigen::Matrix achieved_twist_base = jacobian_base * qdot; - // During a stop, the limiter intentionally commands a near-zero residual - // twist while the measured arm can still be moving in a different direction. - // Direction and speed-ratio checks are not meaningful for that transient. - if (!is_stop_command && - !validateSpeedLCartesianVelocityFeasibility_(speedl_command_twist_base_, - achieved_twist_base, - toEigenVector(q_measured), - qdot)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] cartesian velocity feasibility check failed"; - return false; - } - if (!validateSpeedLJointVelocityCommand_(qdot, reference, dt)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint velocity check failed"; - return false; - } - if (!validateSpeedLPredictedJointPositionLimits_(q_measured, qdot, dt)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] predicted joint position limit check failed"; - return false; - } - const Eigen::VectorXd q_predicted = toEigenVector(q_measured) + qdot * dt; - if (!updateAndValidateSpeedLLineDeviation_(toStdVector(q_predicted), - is_stop_command, - speedl_command_twist_base_.head<3>())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] predicted line deviation check failed"; - return false; - } - - qd_command = toStdVector(qdot); - prev_qdot_command_ = qd_command; - return true; -} - -bool PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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) << "[PinocchioCartesianMotionPlanner][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) << "[PinocchioCartesianMotionPlanner][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 PinocchioCartesianMotionPlanner::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 PinocchioCartesianMotionPlanner::updateSpeedLAcceleration(const double acceleration) -{ - SpeedLOptions options; - options.acceleration = acceleration; - return updateSpeedLLimits(options); -} - -bool PinocchioCartesianMotionPlanner::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); - // Apply the command's motion policy even when acceleration/jerk are - // unchanged. PBVS streams directions; contact retraction locks an axis. - twist_limiter_.setContinuousLinearReversal(options.continuous_linear_reversal.value_or( - !speedl_config_.has_continuous_linear_reversal() || speedl_config_.continuous_linear_reversal())); - if (std::abs(speedl_applied_acceleration_ - acceleration) <= 1e-9 && - std::abs(speedl_applied_angular_acceleration_ - angular_acceleration) <= 1e-9 && - std::abs(speedl_applied_linear_jerk_ - jerk) <= 1e-9) { - return true; - } - - twist_limiter_.setLinearConstraints( - positiveOr(speedl_config_.linear_velocity_max(), .55), - acceleration, jerk); - twist_limiter_.setAngularConstraints( - positiveOr(speedl_config_.angular_velocity_max(), 1.0), - angular_acceleration, positiveOr(speedl_config_.angular_jerk_max(), 12.0)); - speedl_applied_acceleration_ = acceleration; - speedl_applied_angular_acceleration_ = angular_acceleration; - speedl_applied_linear_jerk_ = jerk; - return true; -} - -bool PinocchioCartesianMotionPlanner::captureSpeedLReference( - const std::vector& q, const CartesianVelocity& target, - const FrameType frame, SpeedLReference& reference) -{ - Eigen::Matrix4d pose; - if (!solver_ || !solver_->fk(q, pose, true) || !pose.allFinite()) return false; - auto twist = common::math::velocityToVector(target); - if (frame == FrameType::Tool) { - const Eigen::Matrix3d rotation = pose.block<3, 3>(0, 0); - twist.head<3>() = rotation * twist.head<3>().eval(); - twist.tail<3>() = rotation * twist.tail<3>().eval(); - } else if (frame != FrameType::Base) { - return false; - } - reference.tcp_pose_base = common::math::matrixToPose(pose); - reference.target_base = common::math::vectorToVelocity(twist); - reference.valid = true; - return true; -} - -CartesianVelocity PinocchioCartesianMotionPlanner::getSpeedLCommandTwistBase() const -{ - return common::math::vectorToVelocity(speedl_command_twist_base_); -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp deleted file mode 100644 index 2454b6c6..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" -#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_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; - -// 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())); - } - - struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; }; - Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options, - bool angular = false, int steps = 2200, bool legacy_api = false) { - Peaks peaks; - Twist previous = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - Twist previous_acceleration = Twist::Zero(); - for (int i = 0; i < steps; ++i) { - const bool updated = legacy_api - ? planner_->updateSpeedLAcceleration(options.acceleration) - : planner_->updateSpeedLLimits(options); - if (!updated || !planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)) { - ADD_FAILURE() << "Planning failed at sample " << i; - break; - } - const Twist velocity = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - 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; - } - 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); - std::vector command_; -}; - -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_->updateSpeedLLimits(options)); - options.linear_jerk.reset(); - CartesianVelocity target; - target.vy = 1; - expectPeaks(sample(target, options), .2, .4, 2); -} - -TEST_F(PinocchioSpeedLLimits, LegacyAccelerationAndStopAreCapped) { - SpeedLOptions options; - options.acceleration = 60; - CartesianVelocity target; - target.vy = 1; - expectPeaks(sample(target, options, false, 1200, true), .2, .4, 2); - const auto stop = sample({}, options, false, 1200, true); - EXPECT_LE(stop.velocity, .2); - EXPECT_NEAR(stop.acceleration, .4, 1e-8); - EXPECT_NEAR(stop.jerk, 2, 1e-6); - EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-12); -} - -TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) { - limits_.set_linear_acceleration_max(.2); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - SpeedLOptions options; - options.acceleration = .3; - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - // 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())); - options.acceleration = 60; - expectPeaks(sample(target, options, true), 1, .8, 4); -} - -TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) { - for (double invalid : {0.0, -1.0, std::numeric_limits::infinity(), - std::numeric_limits::quiet_NaN()}) { - SpeedLOptions options; - options.acceleration = invalid; - EXPECT_FALSE(planner_->updateSpeedLLimits(options)); - EXPECT_FALSE(planner_->updateSpeedLAcceleration(invalid)); - options.acceleration = .3; - options.linear_jerk = invalid; - EXPECT_FALSE(planner_->updateSpeedLLimits(options)); - } -} - -TEST_F(PinocchioSpeedLLimits, StreamingAlignmentOverridesGlobalReversalPolicy) { - 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())); - SpeedLOptions options; - options.acceleration = .5; - CartesianVelocity target; - target.vy = .02; - sample(target, options, false, 300); - ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .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; - 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_->updateSpeedLLimits(options)); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - const Twist actual = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - min_speed = std::min(min_speed, actual.head<3>().norm()); - max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm()); - } - EXPECT_NEAR(min_speed, .02, 1e-10); - EXPECT_LT(max_error, 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())); - SpeedLOptions options; - options.acceleration = 1; - options.continuous_linear_reversal = false; - CartesianVelocity target; - target.vy = .02; - sample(target, options, false, 300); - ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10); - - options.continuous_linear_reversal = true; - target.vy = -.02; - for (int i = 0; i < 100; ++i) { - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - } - EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-10); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - EXPECT_LT(planner_->getSpeedLCommandTwistBase().vy, -.0003); -} -} // namespace -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h b/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h deleted file mode 100644 index 97dde369..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef CMVR_ES_TWIST_LIMITER_CONFIG_H -#define CMVR_ES_TWIST_LIMITER_CONFIG_H - -#include - -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" -#include "cmvr/config/arm_config/arm_config.pb.h" -#include "common/config/config_files.h" - -namespace cmvr::device::cartesian_motion { - -inline void configureTwistLimiterFromSpeedLConfig( - cmvr::CartesianTwistLimiter& limiter, - const config::SpeedLPlannerConfig& config) -{ - using cmvr::common::config::positiveOr; - - limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), - positiveOr(config.linear_acceleration_max(), 5.0), - positiveOr(config.linear_jerk_max(), 10.0)); - limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), - positiveOr(config.angular_acceleration_max(), 5.0), - positiveOr(config.angular_jerk_max(), 12.0)); - limiter.setLinearTargetReplanThreshold( - positiveOr(config.linear_target_replan_threshold(), 1e-4)); - limiter.setAngularTargetReplanThreshold( - positiveOr(config.angular_target_replan_threshold(), 1e-4)); - limiter.setLinearReverseSwitchPolicy( - config.linear_reverse_cos_threshold() != 0.0 - ? config.linear_reverse_cos_threshold() - : -0.8660254037844386, - positiveOr(config.linear_reverse_switch_speed_threshold(), 1e-3)); - limiter.setContinuousLinearReversal(!config.has_continuous_linear_reversal() || - config.continuous_linear_reversal()); - limiter.initialize(Eigen::Matrix::Zero()); -} - -inline void updateTwistLimiterAcceleration( - cmvr::CartesianTwistLimiter& limiter, - const config::SpeedLPlannerConfig& config, - const double acceleration) -{ - using cmvr::common::config::positiveOr; - - limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), - std::min(acceleration, positiveOr(config.linear_acceleration_max(), 5.0)), - positiveOr(config.linear_jerk_max(), 10.0)); - limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), - std::min(acceleration, positiveOr(config.angular_acceleration_max(), 5.0)), - positiveOr(config.angular_jerk_max(), 12.0)); -} - -} // namespace cmvr::device::cartesian_motion - -#endif // CMVR_ES_TWIST_LIMITER_CONFIG_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h deleted file mode 100644 index c9211cd1..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H -#define CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H - -#include - -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h" -#include "cmvr/config/arm_config/arm_config.pb.h" - -namespace cmvr::device { - -class JointMotionPlannerFactory { -public: - static std::shared_ptr create( - const config::MoveJConfig& cfg) - { - if (!cfg.has_toppra_joint_motion_planner()) { - return nullptr; - } - - cmvr::PathType path_type; - switch (cfg.toppra_joint_motion_planner().path_type()) { - case config::TOPPRA_PATH_TYPE_LINEAR: - path_type = cmvr::PathType::Linear; - break; - case config::TOPPRA_PATH_TYPE_CUBIC_HERMITE: - path_type = cmvr::PathType::CubicHermite; - break; - case config::TOPPRA_PATH_TYPE_QUINTIC: - path_type = cmvr::PathType::Quintic; - break; - case config::TOPPRA_PATH_TYPE_NATURAL: - path_type = cmvr::PathType::Natural; - break; - case config::TOPPRA_PATH_TYPE_UNKNOWN: - default: - return nullptr; - } - - const auto& toppra = cfg.toppra_joint_motion_planner(); - auto planner = std::make_shared( - path_type, - toppra.sample_period_s(), - toppra.grid_size(), - toppra.high_grid_size()); - if (!planner->init()) { - return nullptr; - } - return planner; - } -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h deleted file mode 100644 index 7aadd085..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H -#define CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H - -#include - -#include "../../joint_motion_planner.h" -#include "../../../../base_motion/joint_trajectory/joint_trajectory_planner.h" - -namespace cmvr::device { - -class ToppraJointMotionPlanner final : public JointMotionPlanner { -public: - ToppraJointMotionPlanner(cmvr::PathType path_type, - double sample_period_s, - int grid_size, - int high_grid_size); - - bool init() override; - - bool planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - double speed_scaling, - JointTrajectory& trajectory) override; - - bool planReplay(const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) override; - -private: - bool sampleTrajectory_( - const std::shared_ptr& planner, - const cmvr::TrajPtr& raw_trajectory, - JointTrajectory& trajectory) const; - - std::shared_ptr planner_; - cmvr::PathType path_type_{cmvr::PathType::Quintic}; - double sample_period_s_{0.001}; - int grid_size_{150}; - int high_grid_size_{300}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp deleted file mode 100644 index 1fe882fa..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp +++ /dev/null @@ -1,258 +0,0 @@ -#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h" - -#include - -#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" -#include "common/base/logging/logger.h" - -namespace cmvr::device { - -namespace { - -std::vector toStdVector(const Eigen::VectorXd& value) -{ - std::vector result; - result.reserve(static_cast(value.size())); - for (int i = 0; i < value.size(); ++i) { - result.push_back(value[i]); - } - return result; -} - -} // namespace - -ToppraJointMotionPlanner::ToppraJointMotionPlanner(const cmvr::PathType path_type, - const double sample_period_s, - const int grid_size, - const int high_grid_size) - : path_type_(path_type) - , sample_period_s_(sample_period_s) - , grid_size_(grid_size) - , high_grid_size_(high_grid_size) -{ -} - -bool ToppraJointMotionPlanner::init() -{ - if (sample_period_s_ <= 0.0 || grid_size_ <= 0 || high_grid_size_ < grid_size_) { - return false; - } - planner_ = std::make_shared(path_type_); - planner_->setGridSizes(grid_size_, high_grid_size_); - return true; -} - -bool ToppraJointMotionPlanner::sampleTrajectory_( - const std::shared_ptr& planner, - const cmvr::TrajPtr& raw_trajectory, - JointTrajectory& trajectory) const -{ - const auto raw_samples = planner->sampleTrajectory( - raw_trajectory, sample_period_s_); - if (raw_samples.size() < 2) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] trajectory sampling returned fewer than " - "two points: count=" - << raw_samples.size(); - return false; - } - trajectory.clear(); - trajectory.reserve(raw_samples.size()); - for (std::size_t i = 0; i < raw_samples.size(); ++i) { - const auto& sample = raw_samples[i]; - if (!std::isfinite(sample.t) || !sample.q.allFinite() || - !sample.qd.allFinite()) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] sampled trajectory contains " - "a non-finite value at point=" - << i; - trajectory.clear(); - return false; - } - JointTrajectoryPoint point; - point.time_s = sample.t; - point.position = toStdVector(sample.q); - point.velocity = toStdVector(sample.qd); - trajectory.push_back(std::move(point)); - } - return true; -} - -bool ToppraJointMotionPlanner::planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - const double speed_scaling, - JointTrajectory& trajectory) -{ - trajectory.clear(); - if (!planner_ || start.empty() || start.size() != target.position.size() || - options.velocity <= 0.0 || options.acceleration <= 0.0) { - return false; - } - - cmvr::TrajPtr raw_trajectory; - planner_->setPathType(path_type_); - planner_->setGridSizes(grid_size_, high_grid_size_); - planner_->setSymmetricLimits( - std::vector(start.size(), options.velocity * speed_scaling), - std::vector(start.size(), options.acceleration)); - if (!planner_->plan(start, target.position, raw_trajectory)) { - return false; - } - - return sampleTrajectory_(planner_, raw_trajectory, trajectory); -} - -bool ToppraJointMotionPlanner::planReplay( - const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) -{ - 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) << "[ToppraJointMotionPlanner][planReplay] 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) << "[ToppraJointMotionPlanner][planReplay] invalid DOF or joint limits"; - return false; - } - for (const double position : current_position) { - if (!std::isfinite(position)) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] 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) << "[ToppraJointMotionPlanner][planReplay] invalid recorded point: " - << i; - return false; - } - for (std::size_t joint = 0; joint < dof; ++joint) { - if (!std::isfinite(point.position[joint])) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] 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) << "[ToppraJointMotionPlanner][planReplay] invalid joint velocity limit"; - return false; - } - } - - const double ramp_duration_s = std::max( - 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; -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp deleted file mode 100644 index 40ad8414..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include -#include -#include -#include -#include - -#include - -#include "joint_motion/toppra/include/toppra_joint_motion_planner.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; -} - -TEST(ToppraJointMotionPlannerTest, PlansBoundedReverseReplay) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - ASSERT_TRUE(planner.init()); - - const JointTrajectory recorded = makeRecordedTrajectory(300); - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory replay; - ASSERT_TRUE(planner.planReplay( - recorded.back().position, recorded, options, replay)); - ASSERT_EQ(replay.size(), recorded.size() + 2); - EXPECT_LT(maximumPositionError( - replay.front().position, recorded.back().position), - 1e-9); - EXPECT_LT(maximumPositionError( - replay.back().position, recorded.front().position), - 1e-9); - for (std::size_t i = 0; i < recorded.size(); ++i) { - EXPECT_LT(maximumPositionError( - replay[i + 1].position, - recorded[recorded.size() - 1 - i].position), - 1e-9); - } - - double maximum_velocity = 0.0; - double maximum_acceleration = 0.0; - for (std::size_t i = 0; i < replay.size(); ++i) { - ASSERT_EQ(replay[i].position.size(), kDof); - ASSERT_EQ(replay[i].velocity.size(), kDof); - for (std::size_t joint = 0; joint < kDof; ++joint) { - maximum_velocity = std::max( - maximum_velocity, std::abs(replay[i].velocity[joint])); - if (i > 0) { - const double dt = replay[i].time_s - replay[i - 1].time_s; - ASSERT_GT(dt, 0.0); - maximum_acceleration = std::max( - maximum_acceleration, - std::abs(replay[i].velocity[joint] - - replay[i - 1].velocity[joint]) / dt); - } - } - } - EXPECT_LE(maximum_velocity, options.velocity + 1e-6); - EXPECT_LE(maximum_acceleration, options.acceleration + 1e-3); -} - -TEST(ToppraJointMotionPlannerTest, RejectsNonIncreasingRecordedTime) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - ASSERT_TRUE(planner.init()); - - JointTrajectory recorded = makeRecordedTrajectory(10); - recorded[5].time_s = recorded[4].time_s; - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory replay; - EXPECT_FALSE(planner.planReplay( - recorded.back().position, recorded, options, replay)); - EXPECT_TRUE(replay.empty()); -} - -TEST(ToppraJointMotionPlannerTest, ValidationRejectsInvalidOutputTrajectory) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory trajectory = makeRecordedTrajectory(10); - trajectory[5].velocity[2] = options.velocity + 0.01; - EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options)); - - trajectory[5].velocity[2] = 0.0; - trajectory[5].time_s = trajectory[4].time_s; - EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options)); -} - -} // namespace -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt deleted file mode 100644 index d815332b..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ - - -add_library(base_motion SHARED - joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp - - motion_profile/s_curve/src/s_curve.cpp - motion_profile/s_curve/src/s_curve_position_planner.cpp - motion_profile/s_curve/src/s_curve_velocity_planner.cpp - cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp -) - -target_include_directories(base_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(base_motion PUBLIC - OsqpEigen - tinyxml2 - fcl - toppra - cmvr_es::common -) - -add_library(cmvr_es::base_motion ALIAS base_motion) -add_executable(cartesian_twist_limiter_reversal_test - cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp) -target_link_libraries(cartesian_twist_limiter_reversal_test PRIVATE - cmvr_es::base_motion gtest gtest_main) -install(TARGETS base_motion LIBRARY DESTINATION lib) - -add_executable(toppra_multi_waypoint_test - joint_trajectory/toppra/test/toppra_multi_waypoint_test.cpp -) - -target_link_libraries(toppra_multi_waypoint_test - PRIVATE - cmvr_es::base_motion - gtest - gtest_main -) - -add_executable(s_curve_velocity_planner_stop_test - motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp -) - -target_link_libraries(s_curve_velocity_planner_stop_test - PRIVATE - cmvr_es::base_motion - gtest - gtest_main -) diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h deleted file mode 100644 index 864f1902..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h +++ /dev/null @@ -1,249 +0,0 @@ -#pragma once - -#include -#include -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h" -namespace cmvr -{ - -enum class CartesianFrame -{ - Base = 0, - Tool = 1 -}; - -/** - * @brief 6维末端 twist 在线限幅器(基于 SCurveVelocityPlanner1D) - * - * 线速度部分: - * - 固定轴上的有符号速度使用 SCurveVelocityPlanner1D 做 jerk-limited 规划 - * - 同轴反向连续过零,保留加速度;可显式选择旧的停止后换向策略 - * - 运动中锁定当前方向,不做方向插值 - * - 若目标方向与当前方向不共线,则采用“先减速到0,再切方向”的 switch policy - * - * 角速度部分: - * - 与线速度独立 - * - 模长使用 SCurveVelocityPlanner1D 做 jerk-limited 速度规划 - * - 运动中锁定当前旋转轴,不做方向插值 - * - * 接口语义: - * - setTargetTwist(...):设置目标 twist - * - synchronizeToMeasuredTwistBase(...):用测量 twist 同步当前状态 - * - update(dt, base_R_tool):根据当前目标与当前状态生成下一拍命令 twist - */ -class CartesianTwistLimiter -{ -public: - using Twist = Eigen::Matrix; - - CartesianTwistLimiter(); - - 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); - - /** - * @brief 设置线速度方向最大转动角速度(rad/s) - */ - void setLinearDirectionRateLimit(double max_rate_rad_s); - - /** - * @brief 设置角速度方向最大转动角速度(rad/s) - */ - void setAngularDirectionRateLimit(double max_rate_rad_s); - - /** - * @brief 设置线速度反向切换策略 - * - * @param cos_threshold 近反向判定阈值,范围 [-1, 1] - * @param switch_speed_threshold 线速度模长低于该阈值后,允许切到目标方向 - */ - void setLinearReverseSwitchPolicy(double cos_threshold, - double switch_speed_threshold); - - // Same-axis reversal uses a signed velocity without resetting acceleration - // at zero. Disable for streaming direction tracking (e.g. visual alignment). - void setContinuousLinearReversal(bool enabled); - bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; } - - /** - * @brief 初始化当前 twist 状态 - * - * 注意: - * - 初始 twist 视为 base 坐标系下 - */ - void initialize(const Twist& initial_twist = Twist::Zero()); - - void reset(); - - /** - * @brief 设置目标 twist - * - * @param target_twist 目标 twist - * @param frame 输入目标的坐标系(Base 或 Tool) - */ - void setTargetTwist(const Twist& target_twist, CartesianFrame frame); - - /** - * @brief 平滑停下 - */ - void stop(); - - /** - * @brief 急停 - * - * 使用更大的减速度/jerk 约束把当前线速度/角速度平滑拉回 0。 - * 当前运动停止后,会自动恢复到常规约束。 - * - * @param emergency_acceleration 急停减速度幅值 - * @param emergency_jerk 急停 jerk 幅值 - */ - void emergencyStop(double emergency_acceleration, - double emergency_jerk); - - /** - * @brief 急停(分别指定线速度/角速度减速度与 jerk) - * - * @param emergency_linear_acceleration 线速度急停减速度幅值 - * @param emergency_linear_jerk 线速度急停 jerk 幅值 - * @param emergency_angular_acceleration 角速度急停减速度幅值 - * @param emergency_angular_jerk 角速度急停 jerk 幅值 - */ - void emergencyStop(double emergency_linear_acceleration, - double emergency_linear_jerk, - double emergency_angular_acceleration, - double emergency_angular_jerk); - - /** - * @brief 用测得的 base-frame twist 同步当前状态 - * - * 作用: - * - 更新当前执行方向 - * - 线速度使用固定轴投影(保留正负号),角速度使用模长 - * - keep_target=true 时: - * - 若测量状态仍贴着当前 profile,则保持当前 profile - * - 否则由 planner 内部从测量状态重规划到当前目标 - * - keep_target=false 时: - * - 清掉旧 profile,仅覆盖状态 - * - * @param measured_twist_base 当前测得实际 twist(base 系) - * @param dt 与上一次测量同步的时间间隔 - * @param keep_target 是否保留当前目标模长 - */ - void synchronize(const Twist& measured_twist_base, - double dt, - bool keep_target = true); - - /** - * @brief 更新一步,返回 base 坐标系下的执行 twist 命令 - */ - Twist update(double dt, const Eigen::Matrix3d& base_R_tool); - - const Twist& getTwistBase() const { return twist_base_; } - const Twist& getCommandedTwistBase() const { return twist_base_; } - const Twist& getTargetTwistBase() const { return target_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 DEFAULT_LINEAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s - static constexpr double DEFAULT_ANGULAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s - static constexpr double DEFAULT_LINEAR_REVERSE_COS_THRESHOLD = -0.8660254037844386; // cos(150 deg) - static constexpr double DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD = 1e-3; - static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999; - static constexpr double DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD = 1e-3; - - // 模长 planner - SCurveVelocityPlanner1D linear_norm_planner_; - SCurveVelocityPlanner1D angular_norm_planner_; - - // 常规约束缓存。急停结束后恢复到这里。 - double linear_max_velocity_; - double linear_max_acceleration_; - double linear_max_jerk_; - double angular_max_velocity_; - double angular_max_acceleration_; - double angular_max_jerk_; - - // 方向变化率限制(rad/s) - double linear_direction_rate_limit_; - double angular_direction_rate_limit_; - - // 线速度 reverse policy - double linear_reverse_cos_threshold_; - double linear_reverse_switch_speed_threshold_; - double angular_switch_speed_threshold_; - bool emergency_stop_active_; - bool continuous_linear_reversal_{true}; - - // 目标/当前状态 - Twist target_twist_input_; - Twist target_twist_base_; - - Twist twist_base_; - Twist acceleration_base_; - Twist jerk_base_; - - Twist prev_twist_base_; - Twist prev_acceleration_base_; - - CartesianFrame input_frame_; - - // 当前执行方向 - Eigen::Vector3d current_linear_dir_base_; - Eigen::Vector3d current_angular_dir_base_; - - // 最近一次非零目标方向(目标变0时用于平滑停下) - Eigen::Vector3d last_target_linear_dir_base_; - Eigen::Vector3d last_target_angular_dir_base_; - - // 测量同步用缓存 - bool has_measured_sync_; - Twist last_measured_twist_base_; - Twist last_measured_acceleration_base_; - double prev_measured_linear_norm_; - double prev_measured_angular_norm_; - - static Twist transformTwistToolToBase(const Twist& twist_tool, - const Eigen::Matrix3d& base_R_tool); - - static Eigen::Vector3d chooseDirection(const Eigen::Vector3d& target_vec, - const Eigen::Vector3d& fallback); - - static Eigen::Vector3d rotateDirectionToward(const Eigen::Vector3d& current_dir, - const Eigen::Vector3d& target_dir, - double max_rate_rad_s, - double dt); - - static Eigen::Vector3d rotateAroundAxis(const Eigen::Vector3d& v, - const Eigen::Vector3d& axis_unit, - double angle_rad); - - static Eigen::Vector3d chooseOrthogonalUnit(const Eigen::Vector3d& v); - - void applyLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - void applyAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - void restoreNominalConstraints(); - static bool isZeroTwist(const Twist& twist); - - static double clamp(double value, double lo, double hi) - { - return std::max(lo, std::min(hi, value)); - } -}; - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp deleted file mode 100644 index 8167c59a..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp +++ /dev/null @@ -1,573 +0,0 @@ -#include "../include/cartesian_twist_limiter.h" - -#include -#include - -namespace cmvr -{ - -CartesianTwistLimiter::CartesianTwistLimiter() - : linear_norm_planner_(1.0, 1.0, 5.0) - , angular_norm_planner_(1.0, 1.0, 5.0) - , linear_max_velocity_(1.0) - , linear_max_acceleration_(1.0) - , linear_max_jerk_(5.0) - , angular_max_velocity_(1.0) - , angular_max_acceleration_(1.0) - , angular_max_jerk_(5.0) - , linear_direction_rate_limit_(DEFAULT_LINEAR_DIR_RATE_LIMIT) - , angular_direction_rate_limit_(DEFAULT_ANGULAR_DIR_RATE_LIMIT) - , linear_reverse_cos_threshold_(DEFAULT_LINEAR_REVERSE_COS_THRESHOLD) - , linear_reverse_switch_speed_threshold_(DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD) - , angular_switch_speed_threshold_(DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD) - , emergency_stop_active_(false) - , target_twist_input_(Twist::Zero()) - , target_twist_base_(Twist::Zero()) - , twist_base_(Twist::Zero()) - , acceleration_base_(Twist::Zero()) - , jerk_base_(Twist::Zero()) - , prev_twist_base_(Twist::Zero()) - , prev_acceleration_base_(Twist::Zero()) - , input_frame_(CartesianFrame::Base) - , current_linear_dir_base_(Eigen::Vector3d::Zero()) - , current_angular_dir_base_(Eigen::Vector3d::Zero()) - , last_target_linear_dir_base_(Eigen::Vector3d::Zero()) - , last_target_angular_dir_base_(Eigen::Vector3d::Zero()) - , has_measured_sync_(false) - , last_measured_twist_base_(Twist::Zero()) - , last_measured_acceleration_base_(Twist::Zero()) - , prev_measured_linear_norm_(0.0) - , prev_measured_angular_norm_(0.0) -{ -} - -void CartesianTwistLimiter::applyLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - linear_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk); -} - -void CartesianTwistLimiter::applyAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - angular_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk); -} - -void CartesianTwistLimiter::setLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - linear_max_velocity_ = std::abs(max_velocity); - linear_max_acceleration_ = std::abs(max_acceleration); - linear_max_jerk_ = std::abs(max_jerk); - - if (!emergency_stop_active_) { - applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_); - } -} - -void CartesianTwistLimiter::setAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - angular_max_velocity_ = std::abs(max_velocity); - angular_max_acceleration_ = std::abs(max_acceleration); - angular_max_jerk_ = std::abs(max_jerk); - - if (!emergency_stop_active_) { - applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_); - } -} - -void CartesianTwistLimiter::setLinearTargetReplanThreshold(double threshold) -{ - linear_norm_planner_.setTargetReplanThreshold(threshold); -} - -void CartesianTwistLimiter::setAngularTargetReplanThreshold(double threshold) -{ - angular_norm_planner_.setTargetReplanThreshold(threshold); -} - -void CartesianTwistLimiter::setLinearDirectionRateLimit(double max_rate_rad_s) -{ - linear_direction_rate_limit_ = std::max(0.0, max_rate_rad_s); -} - -void CartesianTwistLimiter::setAngularDirectionRateLimit(double max_rate_rad_s) -{ - angular_direction_rate_limit_ = std::max(0.0, max_rate_rad_s); -} - -void CartesianTwistLimiter::setLinearReverseSwitchPolicy(double cos_threshold, - double switch_speed_threshold) -{ - linear_reverse_cos_threshold_ = clamp(cos_threshold, -1.0, 1.0); - linear_reverse_switch_speed_threshold_ = std::max(0.0, switch_speed_threshold); -} - -void CartesianTwistLimiter::setContinuousLinearReversal(bool enabled) -{ - if (continuous_linear_reversal_ == enabled) return; - - if (!enabled) { - const double velocity = linear_norm_planner_.getVelocity(); - const double acceleration = linear_norm_planner_.getAcceleration(); - // The streaming policy stores a speed magnitude and a physical direction. - // Convert a negative signed state without reversing its physical motion or - // dropping its acceleration when a command changes policy mid-retraction. - if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) { - current_linear_dir_base_ = -current_linear_dir_base_; - linear_norm_planner_.overwriteState(-velocity, -acceleration, false); - prev_measured_linear_norm_ = -prev_measured_linear_norm_; - } - } - continuous_linear_reversal_ = enabled; -} - -void CartesianTwistLimiter::initialize(const Twist& initial_twist) -{ - restoreNominalConstraints(); - emergency_stop_active_ = false; - - 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(); - - linear_norm_planner_.initialize(v0_norm, 0.0); - angular_norm_planner_.initialize(w0_norm, 0.0); - - target_twist_input_ = initial_twist; - target_twist_base_ = initial_twist; - twist_base_ = initial_twist; - acceleration_base_.setZero(); - jerk_base_.setZero(); - prev_twist_base_ = initial_twist; - prev_acceleration_base_.setZero(); - - // current_linear_dir_base_ = - // (v0_norm > EPSILON) ? (v0 / v0_norm) : Eigen::Vector3d::Zero(); - // current_angular_dir_base_ = - // (w0_norm > EPSILON) ? (w0 / w0_norm) : Eigen::Vector3d::Zero(); - current_linear_dir_base_.setZero(); - current_angular_dir_base_.setZero(); - if (v0_norm > EPSILON) { - current_linear_dir_base_ = v0 / v0_norm; - } else { - - } - - if (w0_norm > EPSILON) { - current_angular_dir_base_ = w0 / w0_norm; - } else { - - } - - last_target_linear_dir_base_ = current_linear_dir_base_; - last_target_angular_dir_base_ = current_angular_dir_base_; - - has_measured_sync_ = false; - last_measured_twist_base_ = initial_twist; - last_measured_acceleration_base_.setZero(); - prev_measured_linear_norm_ = v0_norm; - prev_measured_angular_norm_ = w0_norm; -} - -void CartesianTwistLimiter::reset() -{ - restoreNominalConstraints(); - emergency_stop_active_ = false; - - linear_norm_planner_.reset(); - angular_norm_planner_.reset(); - - target_twist_input_.setZero(); - target_twist_base_.setZero(); - twist_base_.setZero(); - acceleration_base_.setZero(); - jerk_base_.setZero(); - prev_twist_base_.setZero(); - prev_acceleration_base_.setZero(); - - input_frame_ = CartesianFrame::Base; - - current_linear_dir_base_.setZero(); - current_angular_dir_base_.setZero(); - last_target_linear_dir_base_.setZero(); - last_target_angular_dir_base_.setZero(); - - has_measured_sync_ = false; - last_measured_twist_base_.setZero(); - last_measured_acceleration_base_.setZero(); - prev_measured_linear_norm_ = 0.0; - prev_measured_angular_norm_ = 0.0; -} - -void CartesianTwistLimiter::setTargetTwist(const Twist& target_twist, CartesianFrame frame) -{ - if (emergency_stop_active_ && !isZeroTwist(target_twist)) { - restoreNominalConstraints(); - emergency_stop_active_ = false; - } - - target_twist_input_ = target_twist; - input_frame_ = frame; -} - -void CartesianTwistLimiter::stop() -{ - // target_twist_input_.setZero(); - target_twist_input_.setZero(); - target_twist_base_.setZero(); - - linear_norm_planner_.setTargetVelocity(0.0); - angular_norm_planner_.setTargetVelocity(0.0); -} - -void CartesianTwistLimiter::emergencyStop(double emergency_acceleration, - double emergency_jerk) -{ - emergencyStop(emergency_acceleration, - emergency_jerk, - emergency_acceleration, - emergency_jerk); -} - -void CartesianTwistLimiter::emergencyStop(double emergency_linear_acceleration, - double emergency_linear_jerk, - double emergency_angular_acceleration, - double emergency_angular_jerk) -{ - const double linear_stop_acceleration = - std::max(std::abs(emergency_linear_acceleration), linear_max_acceleration_); - const double linear_stop_jerk = - std::max(std::abs(emergency_linear_jerk), linear_max_jerk_); - const double angular_stop_acceleration = - std::max(std::abs(emergency_angular_acceleration), angular_max_acceleration_); - const double angular_stop_jerk = - std::max(std::abs(emergency_angular_jerk), angular_max_jerk_); - - applyLinearConstraints(linear_max_velocity_, linear_stop_acceleration, linear_stop_jerk); - applyAngularConstraints(angular_max_velocity_, angular_stop_acceleration, angular_stop_jerk); - - emergency_stop_active_ = true; - target_twist_input_.setZero(); - target_twist_base_.setZero(); - linear_norm_planner_.setTargetVelocity(0.0); - angular_norm_planner_.setTargetVelocity(0.0); -} - -void CartesianTwistLimiter::synchronize(const Twist& measured_twist_base, - double dt, - bool keep_target) -{ - const Eigen::Vector3d v_meas = measured_twist_base.head<3>(); - const Eigen::Vector3d w_meas = measured_twist_base.tail<3>(); - - const bool signed_linear = continuous_linear_reversal_ && current_linear_dir_base_.norm() > EPSILON; - const double v_norm = signed_linear ? v_meas.dot(current_linear_dir_base_) : v_meas.norm(); - const double w_norm = w_meas.norm(); - - double v_acc = 0.0; - double w_acc = 0.0; - - if (dt > EPSILON && has_measured_sync_) { - v_acc = (v_norm - prev_measured_linear_norm_) / dt; - w_acc = (w_norm - prev_measured_angular_norm_) / dt; - - acceleration_base_ = (measured_twist_base - last_measured_twist_base_) / dt; - jerk_base_ = (acceleration_base_ - last_measured_acceleration_base_) / dt; - last_measured_acceleration_base_ = acceleration_base_; - } else { - acceleration_base_.setZero(); - jerk_base_.setZero(); - last_measured_acceleration_base_.setZero(); - } - - prev_measured_linear_norm_ = v_norm; - prev_measured_angular_norm_ = w_norm; - last_measured_twist_base_ = measured_twist_base; - has_measured_sync_ = true; - - // 线速度按固定轴投影保留正负号;角速度仍按模长同步 planner。 - // keep_target=true: - // - 若测量值仍贴着当前 profile,则继续沿旧 profile 走 - // - 否则从测量状态重规划到当前目标 - // keep_target=false: - // - 仅覆盖状态并清掉旧 profile,不保留当前目标 - if (keep_target) { - linear_norm_planner_.synchronizeAndReplan(v_norm, v_acc); - angular_norm_planner_.synchronizeAndReplan(w_norm, w_acc); - } else { - linear_norm_planner_.overwriteState(v_norm, v_acc, false); - angular_norm_planner_.overwriteState(w_norm, w_acc, false); - target_twist_input_.setZero(); - target_twist_base_.setZero(); - } - - if (!signed_linear && v_norm > EPSILON) { - current_linear_dir_base_ = v_meas / v_norm; - last_target_linear_dir_base_ = current_linear_dir_base_; - } - - if (w_norm > EPSILON) { - current_angular_dir_base_ = w_meas / w_norm; - last_target_angular_dir_base_ = current_angular_dir_base_; - } - - twist_base_ = measured_twist_base; - prev_twist_base_ = measured_twist_base; - prev_acceleration_base_ = acceleration_base_; -} - -CartesianTwistLimiter::Twist -CartesianTwistLimiter::transformTwistToolToBase(const Twist& twist_tool, - const Eigen::Matrix3d& base_R_tool) -{ - Twist twist_base; - twist_base.head<3>() = base_R_tool * twist_tool.head<3>(); - twist_base.tail<3>() = base_R_tool * twist_tool.tail<3>(); - return twist_base; -} - -Eigen::Vector3d CartesianTwistLimiter::chooseDirection(const Eigen::Vector3d& target_vec, - const Eigen::Vector3d& fallback) -{ - const double n = target_vec.norm(); - if (n > EPSILON) { - return target_vec / n; - } - return fallback; -} - -Eigen::Vector3d CartesianTwistLimiter::rotateAroundAxis(const Eigen::Vector3d& v, - const Eigen::Vector3d& axis_unit, - double angle_rad) -{ - const double c = std::cos(angle_rad); - const double s = std::sin(angle_rad); - return c * v + s * (axis_unit.cross(v)) + (1.0 - c) * axis_unit.dot(v) * axis_unit; -} - -Eigen::Vector3d CartesianTwistLimiter::chooseOrthogonalUnit(const Eigen::Vector3d& v) -{ - Eigen::Vector3d ref; - if (std::abs(v.x()) < 0.8) { - ref = Eigen::Vector3d::UnitX(); - } else if (std::abs(v.y()) < 0.8) { - ref = Eigen::Vector3d::UnitY(); - } else { - ref = Eigen::Vector3d::UnitZ(); - } - - Eigen::Vector3d ortho = ref - ref.dot(v) * v; - const double n = ortho.norm(); - if (n > EPSILON) { - return ortho / n; - } - return Eigen::Vector3d::UnitX(); -} - -void CartesianTwistLimiter::restoreNominalConstraints() -{ - applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_); - applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_); -} - -bool CartesianTwistLimiter::isZeroTwist(const Twist& twist) -{ - return twist.head<3>().squaredNorm() <= EPSILON && twist.tail<3>().squaredNorm() <= EPSILON; -} - -Eigen::Vector3d CartesianTwistLimiter::rotateDirectionToward(const Eigen::Vector3d& current_dir, - const Eigen::Vector3d& target_dir, - double max_rate_rad_s, - double dt) -{ - if (dt <= 0.0) { - return current_dir; - } - - const double cur_n = current_dir.norm(); - const double tgt_n = target_dir.norm(); - - if (tgt_n <= EPSILON) { - return current_dir; - } - if (cur_n <= EPSILON) { - return target_dir; - } - - const Eigen::Vector3d u = current_dir / cur_n; - const Eigen::Vector3d v = target_dir / tgt_n; - - const double dot_uv = clamp(u.dot(v), -1.0, 1.0); - const double angle = std::acos(dot_uv); - - if (angle <= 1e-9) { - return v; - } - - const double max_step = std::max(0.0, max_rate_rad_s) * dt; - if (max_step <= 0.0) { - return u; - } - if (angle <= max_step) { - return v; - } - - Eigen::Vector3d axis = u.cross(v); - const double axis_n = axis.norm(); - - if (axis_n > EPSILON) { - axis /= axis_n; - return rotateAroundAxis(u, axis, max_step).normalized(); - } - - if (dot_uv > 0.0) { - return v; - } - - const Eigen::Vector3d ortho_axis = chooseOrthogonalUnit(u); - return rotateAroundAxis(u, ortho_axis, max_step).normalized(); -} - -CartesianTwistLimiter::Twist -CartesianTwistLimiter::update(double dt, const Eigen::Matrix3d& base_R_tool) -{ - if (emergency_stop_active_ && isZeroTwist(target_twist_input_) && - !linear_norm_planner_.isMoving() && !angular_norm_planner_.isMoving()) { - restoreNominalConstraints(); - emergency_stop_active_ = false; - } - - if (input_frame_ == CartesianFrame::Base) { - target_twist_base_ = target_twist_input_; - } else { - target_twist_base_ = transformTwistToolToBase(target_twist_input_, base_R_tool); - } - - // ==================== 线速度:方向锁定 + 标量 planner ==================== - const Eigen::Vector3d v_des = target_twist_base_.head<3>(); - const double v_des_norm = v_des.norm(); - const Eigen::Vector3d v_target_dir = - chooseDirection(v_des, - current_linear_dir_base_.norm() > EPSILON - ? current_linear_dir_base_ - : last_target_linear_dir_base_); - - if (v_des_norm > EPSILON) { - last_target_linear_dir_base_ = v_target_dir; - } - - const double v_cur_norm = linear_norm_planner_.getVelocity(); - const bool has_current_linear_dir = current_linear_dir_base_.norm() > EPSILON; - if (!has_current_linear_dir) { - if (v_des_norm > EPSILON) { - current_linear_dir_base_ = v_target_dir; - linear_norm_planner_.setTargetVelocity(v_des_norm); - } else { - linear_norm_planner_.setTargetVelocity(0.0); - } - } else if (v_des_norm <= EPSILON) { - linear_norm_planner_.setTargetVelocity(0.0); - } else { - const double dir_dot = - clamp(current_linear_dir_base_.dot(v_target_dir), -1.0, 1.0); - const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD; - const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD; - const bool same_axis = axis_aligned || reverse_aligned; - const bool must_switch_axis = - !same_axis || dir_dot < linear_reverse_cos_threshold_; - - if (continuous_linear_reversal_ && same_axis) { - // Keep the axis fixed: the scalar profile carries the direction sign. - // Crossing zero is an interior point, with continuous acceleration. - linear_norm_planner_.setTargetVelocity(v_des.dot(current_linear_dir_base_)); - } else if (continuous_linear_reversal_ && - (std::abs(v_cur_norm) > EPSILON || - std::abs(linear_norm_planner_.getAcceleration()) > EPSILON || - linear_norm_planner_.hasActiveProfile())) { - // A different axis may only be adopted after the old profile settles. - linear_norm_planner_.setTargetVelocity(0.0); - } else if (!continuous_linear_reversal_ && must_switch_axis && - v_cur_norm > linear_reverse_switch_speed_threshold_) { - linear_norm_planner_.setTargetVelocity(0.0); - } else { - current_linear_dir_base_ = v_target_dir; - linear_norm_planner_.setTargetVelocity(v_des_norm); - } - } - - const double v_exec_norm = linear_norm_planner_.update(dt); - twist_base_.head<3>() = current_linear_dir_base_ * v_exec_norm; - - // ==================== 角速度:方向锁定 + 标量 planner ==================== - const Eigen::Vector3d w_des = target_twist_base_.tail<3>(); - const double w_des_norm = w_des.norm(); - const Eigen::Vector3d w_target_dir = - chooseDirection(w_des, - current_angular_dir_base_.norm() > EPSILON - ? current_angular_dir_base_ - : last_target_angular_dir_base_); - - if (w_des_norm > EPSILON) { - last_target_angular_dir_base_ = w_target_dir; - } - - const double w_cur_norm = angular_norm_planner_.getVelocity(); - const bool has_current_angular_dir = current_angular_dir_base_.norm() > EPSILON; - if (!has_current_angular_dir) { - if (w_des_norm > EPSILON) { - current_angular_dir_base_ = w_target_dir; - angular_norm_planner_.setTargetVelocity(w_des_norm); - } else { - angular_norm_planner_.setTargetVelocity(0.0); - } - } else if (w_des_norm <= EPSILON) { - angular_norm_planner_.setTargetVelocity(0.0); - } else { - const double dir_dot = - clamp(current_angular_dir_base_.dot(w_target_dir), -1.0, 1.0); - const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD; - const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD; - const bool same_axis = axis_aligned || reverse_aligned; - // 角速度与线速度一致:反向同轴也必须先减速到 0,再切方向。 - const bool must_switch_axis = !same_axis || reverse_aligned; - - if (must_switch_axis && w_cur_norm > angular_switch_speed_threshold_) { - angular_norm_planner_.setTargetVelocity(0.0); - } else { - current_angular_dir_base_ = w_target_dir; - angular_norm_planner_.setTargetVelocity(w_des_norm); - } - } - - const double w_exec_norm = angular_norm_planner_.update(dt); - twist_base_.tail<3>() = current_angular_dir_base_ * w_exec_norm; - - // ==================== 对最终 twist 做差分得到 acc / jerk ==================== - if (dt > EPSILON) { - acceleration_base_ = (twist_base_ - prev_twist_base_) / dt; - jerk_base_ = (acceleration_base_ - prev_acceleration_base_) / dt; - } else { - acceleration_base_.setZero(); - jerk_base_.setZero(); - } - - prev_twist_base_ = twist_base_; - prev_acceleration_base_ = acceleration_base_; - - return twist_base_; -} - -bool CartesianTwistLimiter::isMoving() const -{ - return linear_norm_planner_.isMoving() || angular_norm_planner_.isMoving(); -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp deleted file mode 100644 index 18ba446f..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" - -namespace cmvr { -namespace { -using Twist = CartesianTwistLimiter::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) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(.55, 5, 10); - limiter.setContinuousLinearReversal(continuous); - limiter.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero()); - limiter.setTargetTwist(y(.08), CartesianFrame::Base); - for (int i = 0; i < approach_ticks; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - limiter.setLinearConstraints(.55, 3, 10); - limiter.setTargetTwist(y(-.08), CartesianFrame::Base); - Motion result; - double position = 0; - for (int i = 1; i <= 1500; ++i) { - const auto v = limiter.update(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(limiter.getAccelerationBase().norm(), 3.0 + 1e-7); - EXPECT_LE(limiter.getJerkBase().norm(), 10.0 + 1e-6); - EXPECT_NEAR(v.x(), 0, 1e-12); - EXPECT_NEAR(v.z(), 0, 1e-12); - } - } - EXPECT_NEAR(limiter.getTwistBase().y(), -.08, 1e-9); - return result; -} -TEST(CartesianTwistReversal, 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(CartesianTwistReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 1, 4); - limiter.initialize(y(.02)); - limiter.setTargetTwist(y(-.02), CartesianFrame::Base); - for (int i = 0; i < 100; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_NEAR(limiter.getTwistBase().y(), 0, 1e-12); - EXPECT_TRUE(limiter.isMoving()); - EXPECT_LT(limiter.getAccelerationBase().y(), -.39); - EXPECT_LT(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.0003); -} -TEST(CartesianTwistReversal, StopFromEitherDirectionSettlesWithoutReversing) { - for (double v : {.08, -.08}) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(v)); - limiter.stop(); - for (int i = 0; i < 1000; ++i) { - EXPECT_GE(limiter.update(dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12); - } - EXPECT_FALSE(limiter.isMoving()); - EXPECT_NEAR(limiter.getTwistBase().norm(), 0, 1e-12); - } -} -TEST(CartesianTwistReversal, FeedbackPreservesNegativeVelocityOnLockedAxis) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(.08)); - limiter.setTargetTwist(y(-.08), CartesianFrame::Base); - for (int i = 0; i < 400; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - for (int i = 0; i < 10; ++i) { - limiter.synchronize(y(-.08), dt, true); - EXPECT_NEAR(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.08, 1e-9); - } -} -TEST(CartesianTwistReversal, NonCollinearChangeStopsBeforeSwitchingAxis) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(.08)); - Twist x = Twist::Zero(); x.x() = .08; - limiter.setTargetTwist(x, CartesianFrame::Base); - for (int i = 0; i < 1000; ++i) { - const auto v = limiter.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_FALSE(v.x() > 1e-9 && std::abs(v.y()) > 1e-9); - EXPECT_LE(limiter.getJerkBase().norm(), 10 + 1e-6); - } - EXPECT_NEAR(limiter.getTwistBase().x(), .08, 1e-9); -} - -TEST(CartesianTwistReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) { - for (const int reverse_ticks : {150, 250, 500}) { - SCOPED_TRACE(reverse_ticks); - CartesianTwistLimiter reference; - reference.setLinearConstraints(1, 3, 10); - reference.initialize(y(.08)); - reference.setTargetTwist(y(-.08), CartesianFrame::Base); - for (int i = 0; i < reverse_ticks; ++i) reference.update(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.update(dt, Eigen::Matrix3d::Identity()); - const auto actual = streaming.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_NEAR((actual - expected).norm(), 0, 1e-9); - EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6); - } - } -} -} -} diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h deleted file mode 100644 index fcb64bb7..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Created by lgv on 11/7/25. -// - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace cmvr { - // 统一轨迹接口 - struct ITrajectory { - virtual ~ITrajectory() = default; - virtual toppra::Bound timeInterval() const = 0; - virtual Eigen::VectorXd q(double t) const = 0; - virtual Eigen::VectorXd qd(double t) const = 0; - virtual Eigen::VectorXd qdd(double t) const = 0; - }; - using TrajPtr = std::shared_ptr; - - struct TrajSample { - double t{}; - Eigen::VectorXd q; // DoF x 1 - Eigen::VectorXd qd; // DoF x 1 - Eigen::VectorXd qdd; // DoF x 1 - }; - - // 三种几何路径 - enum class PathType { Linear, - CubicHermite, - Quintic, - // 三次B样条 - Natural }; - class JointTrajectoryPlanner { - public: - - explicit JointTrajectoryPlanner(PathType p):path_type_(p){}; - JointTrajectoryPlanner()=default; - virtual ~JointTrajectoryPlanner() = default; - - virtual bool plan(const std::vector& start_joints, - const std::vector& goal_joints, - TrajPtr& traj) { - return false; - } - - virtual bool plan(const std::vector>& waypoints, TrajPtr& traj){ - return false; - } - - // 采样函数:从 ITrajectory 生成采样序列 dt(s) - virtual std::vector sampleTrajectory(const TrajPtr& traj, double dt) { - - return {}; - } - - virtual bool writeTrajectoryCsv(const std::string& filename,const std::vector& samples) { - - return false; - } - - // 对称限:[-v_max, v_max]、[-a_max, a_max] - virtual void setSymmetricLimits(const std::vector &v_max,const std::vector &a_max){ - v_max_ = v_max; - a_max_ = a_max; - } - - // 可调网格密度(默认 150/300) - virtual void setGridSizes(int N, int N_high) - { - N_grid_ = N; - N_grid_high_ = N_high; - } - - // 切换几何路径类型 - virtual void setPathType(PathType p){path_type_ = p;} - protected: - PathType path_type_{PathType::Quintic}; - int N_grid_ = 150; - int N_grid_high_ = 300; - std::vector v_max_, a_max_; - - }; -} diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h deleted file mode 100644 index f344fc1e..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h +++ /dev/null @@ -1,209 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "../../joint_trajectory_planner.h" -#include -#include -#include - -namespace cmvr { - // 适配器:ConstAccel - class ConstAccelTraj : public ITrajectory { - public: - explicit ConstAccelTraj(std::shared_ptr p); - - toppra::Bound timeInterval() const override; - - Eigen::VectorXd q(double t) const override; - - Eigen::VectorXd qd(double t) const override; - - Eigen::VectorXd qdd(double t) const override; - - private: - std::shared_ptr impl_; - }; - - // 适配器:Spline - class SplineTraj : public ITrajectory { - public: - SplineTraj(const std::shared_ptr &path, - const toppra::Vector &grid, - const toppra::Vector &vsq); - - toppra::Bound timeInterval() const override; - - Eigen::VectorXd q(double t) const override; - - Eigen::VectorXd qd(double t) const override; - - Eigen::VectorXd qdd(double t) const override; - - private: - toppra::parametrizer::Spline impl_; - }; - - // 具体规划器:一次/三次/五次可切换;ConstAccel 校验失败自动回退 Spline - class ToppraJointTrajectoryPlanner : public JointTrajectoryPlanner { - public: - explicit ToppraJointTrajectoryPlanner(PathType type = PathType::Quintic); - - - // 统一入口:两点/多点皆可 - bool plan(const std::vector > &waypoints, TrajPtr &traj_out) override; - - // 兼容旧 API(可选):转发为两点的统一入口 - bool plan(const std::vector &start_joints, - const std::vector &goal_joints, - TrajPtr &traj_out) override; - - std::vector sampleTrajectory(const TrajPtr &traj, double dt) override; - - bool writeTrajectoryCsv(const std::string &filename, const std::vector &samples) override; - - private: - // —— 几何路径统一分发 —— - std::shared_ptr - buildPathUnified(const std::vector &q, - const std::vector &S); - - // 二点专用 - std::shared_ptr - buildTwoPointPath(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildLinearTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildCubicHermiteTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildQuinticRestToRestTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildNaturalTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - // 多点 - std::shared_ptr - buildLinearMulti(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildCubicHermiteMulti(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildQuinticC2Multi(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildNaturalMulti(const std::vector &q, - const std::vector &S); - - // —— 工具:限幅/参数/估计 —— - bool ensureLimitsSized(std::size_t DoF); - - static void sanitizeVsq(toppra::Vector &v); - - - // Joint-space chord length keeps the parameterization independent of - // how densely the same geometric path is sampled. - static std::vector - makeSChordLength(const std::vector &q) { - const size_t M = q.size(); - std::vector S(M, 0.0); - for (size_t i = 1; i < M; ++i) { - S[i] = S[i - 1] + (q[i] - q[i - 1]).norm(); - } - return S; - } - - // Catmull–Rom(centripetal)估计结点几何速度 v(端点=0) - static std::vector - estimateVelsCatmull(const std::vector &q, - const std::vector &S) { - const size_t M = q.size(); - const int DoF = static_cast(q[0].size()); - std::vector v(M, Eigen::VectorXd::Zero(DoF)); - if (M <= 2) return v; - for (size_t i = 1; i + 1 < M; ++i) { - double ds0 = std::max(S[i] - S[i - 1], 1e-12); - double ds1 = std::max(S[i + 1] - S[i], 1e-12); - v[i] = ((q[i + 1] - q[i]) / ds1 * ds0 + (q[i] - q[i - 1]) / ds0 * ds1) / (ds0 + ds1); - } - return v; - } - - // 对内点几何速度限幅,抑制过冲(k∈[0.5,1.0]) - static void clampNodeVels(std::vector &v, - const std::vector &q, - const std::vector &S, - double k = 1.0) { - const size_t M = q.size(); - if (M <= 2) return; - for (size_t i = 1; i + 1 < M; ++i) { - const double ds0 = std::max(S[i] - S[i - 1], 1e-12); - const double ds1 = std::max(S[i + 1] - S[i], 1e-12); - const double slope0 = (q[i] - q[i - 1]).norm() / ds0; - const double slope1 = (q[i + 1] - q[i]).norm() / ds1; - const double vmax = k * std::min(slope0, slope1); - double n = v[i].norm(); - if (n > vmax) v[i] *= (vmax / n); - } - } - - // 估计结点几何加速度 a(端点=0;中点二阶差分,按 s 尺度) - static std::vector - estimateAccelsSecondDiff(const std::vector &q, - const std::vector &S) { - const size_t M = q.size(); - const int DoF = static_cast(q[0].size()); - std::vector a(M, Eigen::VectorXd::Zero(DoF)); - if (M <= 2) return a; - for (size_t i = 1; i + 1 < M; ++i) { - double h0 = std::max(S[i] - S[i - 1], 1e-12); // 左间距 - double h1 = std::max(S[i + 1] - S[i], 1e-12); // 右间距 - double denom = 0.5 * (h0 + h1); // 局部尺度 - // 非均匀中心二阶差分(更精确): - // a ≈ 2 * [ (q_{i+1}-q_i)/h1 - (q_i - q_{i-1})/h0 ] / (h0 + h1) - a[i] = 2.0 * ((q[i + 1] - q[i]) / h1 - (q[i] - q[i - 1]) / h0) / (h0 + h1); - } - return a; - } - - - // τ→s 变元:把局部 Quintic(τ) 的系数 c_tau[0..5](τ^0..τ^5) - // 变成全局 s 的系数 alpha[0..5](s^0..s^5),其中 τ = (s - S_k) / ds - static inline void localQuinticToGlobalCoeffs( - const std::array &c_tau, // c0..c5(DoF维向量) - double Sk, double ds, - std::array &alpha // α0..α5(DoF维向量) - ) { - static const double C[6][6] = { - // binomial(n,m) - {1, 0, 0, 0, 0, 0}, - {1, 1, 0, 0, 0, 0}, - {1, 2, 1, 0, 0, 0}, - {1, 3, 3, 1, 0, 0}, - {1, 4, 6, 4, 1, 0}, - {1, 5, 10, 10, 5, 1} - }; - const double eps = 1e-12; - ds = std::max(ds, eps); - - for (int m = 0; m <= 5; ++m) alpha[m].setZero(c_tau[0].size()); - - // α_m = Σ_{n=m..5} c_n * C(n,m) * (-S_k)^{n-m} / ds^{n} - for (int n = 0; n <= 5; ++n) { - double invdsn = std::pow(ds, -n); - for (int m = 0; m <= n; ++m) { - double factor = C[n][m] * std::pow(-Sk, n - m) * invdsn; - alpha[m].noalias() += factor * c_tau[n]; - } - } - } - }; -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp deleted file mode 100644 index 040b59e1..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp +++ /dev/null @@ -1,527 +0,0 @@ -#include -#include -#include -#include -#include -#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" - -#include -#include -#include -#include - -namespace cmvr { - namespace { - - class TimeScaledTrajectory final : public ITrajectory { - public: - TimeScaledTrajectory(TrajPtr source, const double scale) - : source_(std::move(source)), scale_(scale), source_interval_(source_->timeInterval()) - { - } - - toppra::Bound timeInterval() const override - { - toppra::Bound interval; - interval << source_interval_[0], - source_interval_[0] + - (source_interval_[1] - source_interval_[0]) * scale_; - return interval; - } - - Eigen::VectorXd q(const double t) const override - { - return source_->q(sourceTime_(t)); - } - - Eigen::VectorXd qd(const double t) const override - { - return source_->qd(sourceTime_(t)) / scale_; - } - - Eigen::VectorXd qdd(const double t) const override - { - return source_->qdd(sourceTime_(t)) / (scale_ * scale_); - } - - private: - double sourceTime_(const double output_time) const - { - return std::clamp( - source_interval_[0] + - (output_time - source_interval_[0]) / scale_, - source_interval_[0], - source_interval_[1]); - } - - TrajPtr source_; - double scale_{1.0}; - toppra::Bound source_interval_; - }; - - bool enforceSampledLimits(const TrajPtr& source, - const std::vector& velocity_limits, - const std::vector& acceleration_limits, - const std::size_t waypoint_count, - TrajPtr& output) - { - if (!source || velocity_limits.empty() || - velocity_limits.size() != acceleration_limits.size()) { - return false; - } - const auto interval = source->timeInterval(); - const double duration = interval[1] - interval[0]; - if (!std::isfinite(duration) || duration <= 0.0) { - return false; - } - - const std::size_t time_samples = static_cast( - std::ceil(duration / 0.001)) + 1; - const std::size_t path_samples = waypoint_count * 20; - const std::size_t sample_count = std::clamp( - std::max({std::size_t{1000}, time_samples, path_samples}), - std::size_t{1000}, - std::size_t{200000}); - - double required_scale = 1.0; - for (std::size_t sample = 0; sample < sample_count; ++sample) { - const double ratio = static_cast(sample) / - static_cast(sample_count - 1); - const double time = interval[0] + duration * ratio; - const Eigen::VectorXd velocity = source->qd(time); - const Eigen::VectorXd acceleration = source->qdd(time); - if (!velocity.allFinite() || !acceleration.allFinite() || - velocity.size() != static_cast(velocity_limits.size()) || - acceleration.size() != - static_cast(acceleration_limits.size())) { - return false; - } - for (Eigen::Index joint = 0; joint < velocity.size(); ++joint) { - const std::size_t index = static_cast(joint); - required_scale = std::max( - required_scale, - std::abs(velocity[joint]) / velocity_limits[index]); - required_scale = std::max( - required_scale, - std::sqrt(std::abs(acceleration[joint]) / - acceleration_limits[index])); - } - } - - constexpr double kNumericalMargin = 1.001; - output = std::make_shared( - source, required_scale * kNumericalMargin); - return true; - } - - } // namespace - - // ===== ConstAccelTraj ===== - ConstAccelTraj::ConstAccelTraj(std::shared_ptr p) - : impl_(std::move(p)) { - } - - toppra::Bound ConstAccelTraj::timeInterval() const { return impl_->pathInterval(); } - Eigen::VectorXd ConstAccelTraj::q(double t) const { return impl_->eval_single(t, 0); } - Eigen::VectorXd ConstAccelTraj::qd(double t) const { return impl_->eval_single(t, 1); } - Eigen::VectorXd ConstAccelTraj::qdd(double t) const { return impl_->eval_single(t, 2); } - - // ===== SplineTraj ===== - SplineTraj::SplineTraj(const std::shared_ptr &path, - const toppra::Vector &grid, - const toppra::Vector &vsq) - : impl_(path, grid, vsq) { - } - - toppra::Bound SplineTraj::timeInterval() const { return impl_.pathInterval(); } - Eigen::VectorXd SplineTraj::q(double t) const { return impl_.eval_single(t, 0); } - Eigen::VectorXd SplineTraj::qd(double t) const { return impl_.eval_single(t, 1); } - Eigen::VectorXd SplineTraj::qdd(double t) const { return impl_.eval_single(t, 2); } - - // ===== ToppraJointTrajectoryPlanner ===== - ToppraJointTrajectoryPlanner::ToppraJointTrajectoryPlanner(PathType type) :JointTrajectoryPlanner(type) { - } - - - - bool ToppraJointTrajectoryPlanner::ensureLimitsSized(std::size_t DoF) { - if (v_max_.size() != DoF) v_max_.assign(DoF, 1.5); - if (a_max_.size() != DoF) a_max_.assign(DoF, 3.0); - return true; - } - - void ToppraJointTrajectoryPlanner::sanitizeVsq(toppra::Vector &v) { - for (int i = 0; i < v.size(); ++i) if (v[i] < 0 && v[i] > -1e-10) v[i] = 0; - if (v.size() > 0) { - v[0] = 0; - v[v.size() - 1] = 0; - } - } - // ===== 统一入口:两点/多点 ===== - bool ToppraJointTrajectoryPlanner::plan(const std::vector>& waypoints, - TrajPtr& traj_out) { - traj_out.reset(); - if (waypoints.size() < 2) return false; - const size_t DoF = waypoints.front().size(); - if (DoF == 0) return false; - for (const auto& w : waypoints) { - if (w.size() != DoF) return false; - for (const double value : w) { - if (!std::isfinite(value)) return false; - } - } - if (!ensureLimitsSized(DoF)) return false; - for (size_t joint = 0; joint < DoF; ++joint) { - if (!std::isfinite(v_max_[joint]) || v_max_[joint] <= 0.0 || - !std::isfinite(a_max_[joint]) || a_max_[joint] <= 0.0) { - return false; - } - } - - std::vector q; - q.reserve(waypoints.size()); - constexpr double kDuplicateDistance = 1e-10; - for (const auto& waypoint : waypoints) { - Eigen::VectorXd value = Eigen::Map( - waypoint.data(), static_cast(DoF)); - if (q.empty() || (value - q.back()).norm() > kDuplicateDistance) { - q.push_back(std::move(value)); - } - } - if (q.size() < 2) return false; - const size_t M = q.size(); - - const std::vector S = M == 2 - ? std::vector{0.0, 1.0} - : makeSChordLength(q); - - // 几何路径 - auto path = buildPathUnified(q, S); - if (!path) return false; - - // 约束 - Eigen::VectorXd vmax(DoF), amax(DoF); - for (size_t i=0;i(-vmax, vmax); - auto acc = std::make_shared(-amax, amax); - vel->discretizationType(toppra::DiscretizationType::Collocation); - acc->discretizationType(toppra::DiscretizationType::Interpolation); - toppra::LinearConstraintPtrs constraints{vel, acc}; - - // TOPPRA - toppra::algorithm::TOPPRA algo{constraints, path}; - auto solve_once = [&](const int requested_intervals)->bool{ - const int segment_count = static_cast(M - 1); - const int subdivisions = std::max( - 1, (requested_intervals + segment_count - 1) / segment_count); - toppra::Vector grid(segment_count * subdivisions + 1); - Eigen::Index index = 0; - for (int segment = 0; segment < segment_count; ++segment) { - const double start = S[static_cast(segment)]; - const double length = S[static_cast(segment + 1)] - start; - for (int subdivision = 0; subdivision < subdivisions; ++subdivision) { - grid[index++] = start + length * - static_cast(subdivision) / - static_cast(subdivisions); - } - } - grid[index] = S.back(); - algo.setGridpoints(grid); - algo.solver(std::make_shared()); - return algo.computePathParametrization(0.0, 0.0) == toppra::ReturnCode::OK; - }; - if (!solve_once(N_grid_)) { - if (!solve_once(N_grid_high_)) return false; - } - - const auto data = algo.getParameterizationData(); - toppra::Vector grid = data.gridpoints; - toppra::Vector vsq = data.parametrization; - - TrajPtr candidate; - auto ca = std::make_shared(path, grid, vsq); - if (ca->validate()) { - candidate = std::make_shared(std::move(ca)); - } else { - sanitizeVsq(vsq); - try { - candidate = std::make_shared(path, grid, vsq); - (void) candidate->timeInterval(); - } catch (...) { - return false; - } - } - return enforceSampledLimits(candidate, v_max_, a_max_, M, traj_out); - } - - - bool ToppraJointTrajectoryPlanner::plan(const std::vector& start_joints, - const std::vector& goal_joints, - TrajPtr& traj_out) { - if (start_joints.empty() || start_joints.size()!=goal_joints.size()) return false; - std::vector> wpts{start_joints, goal_joints}; - return plan(wpts, traj_out); - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildPathUnified(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(); - if (M == 2) return buildTwoPointPath(q[0], q[1]); - switch (path_type_) { - case PathType::Linear: return buildLinearMulti(q, S); - case PathType::CubicHermite: return buildCubicHermiteMulti(q, S); - case PathType::Natural: return buildNaturalMulti(q, S); - case PathType::Quintic: - default: return buildQuinticC2Multi(q, S); - } - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildTwoPointPath(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - switch (path_type_) { - case PathType::Linear: return buildLinearTwo(q0, q1); - case PathType::CubicHermite: return buildCubicHermiteTwo(q0, q1); - case PathType::Natural: return buildNaturalTwo(q0, q1); - case PathType::Quintic: - default: return buildQuinticRestToRestTwo(q0, q1); - } - } - - // 二点:Linear —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildLinearTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - const size_t DoF = static_cast(q0.size()); - toppra::Matrix seg(2, DoF); - seg.row(0) = (q1 - q0).transpose(); - seg.row(1) = q0.transpose(); - return std::make_shared( - toppra::Matrices{seg}, std::vector{0.0, 1.0}); - } - - // 二点:Cubic Hermite(端点速度 0) —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildCubicHermiteTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - toppra::Vectors pos{q0, q1}; - toppra::Vectors vel{Eigen::VectorXd::Zero(q0.size()), - Eigen::VectorXd::Zero(q1.size())}; - std::vector s{0.0, 1.0}; - auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, s); - return std::make_shared(herm); - } - - // 二点:Quintic rest-to-rest —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildQuinticRestToRestTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - const size_t DoF = static_cast(q0.size()); - const Eigen::VectorXd dq = q1 - q0; - toppra::Matrix seg(6, DoF); // x^5..x^0 - seg.row(0) = ( 6.0 * dq).transpose(); - seg.row(1) = (-15.0 * dq).transpose(); - seg.row(2) = (10.0 * dq).transpose(); - seg.row(3).setZero(); seg.row(4).setZero(); - seg.row(5) = q0.transpose(); - return std::make_shared( - toppra::Matrices{seg}, std::vector{0.0, 1.0}); - } - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildNaturalTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - using PWP = toppra::PiecewisePolyPath; - - // positions(两点) - toppra::Vectors pos{ q0, q1 }; - - // 自变量S:两点用等距最简单 - toppra::Vector S(2); - S[0] = 0.0; S[1] = 1.0; - - - toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"), - toppra::BoundaryCond("clamped") }; - auto path = PWP::CubicSpline(pos, S, bcA); - return std::make_shared(path); - - // 手动指定二阶导为 0 - // const int DoF = static_cast(q0.size()); - // toppra::BoundaryCondFull bcB = { - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)), - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)) - // }; - // auto path2 = PWP::CubicSpline(pos, S, bcB); - // return std::make_shared(path2); - } - - - // —— 多点:Linear —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildLinearMulti(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(), DoF = q[0].size(); - toppra::Matrices segs; segs.reserve(M-1); - for (size_t k=0;k+1(S[k+1]-S[k], 1e-12); - toppra::Matrix seg(2, DoF); - Eigen::RowVectorXd A1 = ((q[k+1]-q[k])/ds).transpose(); - Eigen::RowVectorXd A0 = q[k].transpose(); - seg.row(0)=A1; seg.row(1)=A0; - segs.emplace_back(std::move(seg)); - } - return std::make_shared(segs, std::vector(S.begin(), S.end())); - } - - // —— 多点:Cubic Hermite —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildCubicHermiteMulti(const std::vector& q, - const std::vector& S) { - auto v = estimateVelsCatmull(q, S); - clampNodeVels(v, q, S, /*k=*/1.0); - toppra::Vectors pos(q.begin(), q.end()); - toppra::Vectors vel(v.begin(), v.end()); - auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, S); - return std::make_shared(herm); - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildNaturalMulti(const std::vector& q, - const std::vector& S) { - using PWP = toppra::PiecewisePolyPath; - - const size_t M = q.size(); - if (M < 2 || M != S.size()) return nullptr; - - // positions - toppra::Vectors pos(q.begin(), q.end()); - - // times(全局自变量,需严格递增) - toppra::Vector times(static_cast(M)); - for (size_t i = 0; i < M; ++i) times[static_cast(i)] = S[i]; - - //Natural - toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"), - toppra::BoundaryCond("clamped") }; - auto path = PWP::CubicSpline(pos, times, bcA); - return std::make_shared(path); - - // 手动指定二阶导为 0 —— - // const int DoF = static_cast(q[0].size()); - // toppra::BoundaryCondFull bcB = { - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)), - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)) - // }; - // auto path2 = PWP::CubicSpline(pos, times, bcB); - // return std::make_shared(path2); - } - - // —— 多点:Quintic C² —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildQuinticC2Multi(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(), DoF = q[0].size(); - auto v = estimateVelsCatmull(q, S); - clampNodeVels(v, q, S, /*k=*/1.0); - auto a = estimateAccelsSecondDiff(q, S); - - toppra::Matrices segs; segs.reserve(M-1); - for (size_t k=0;k+1(S[k+1]-S[k], 1e-12); - const Eigen::VectorXd& q0=q[k]; const Eigen::VectorXd& q1=q[k+1]; - const Eigen::VectorXd& v0=v[k]; const Eigen::VectorXd& v1=v[k+1]; - const Eigen::VectorXd& a0=a[k]; const Eigen::VectorXd& a1=a[k+1]; - const Eigen::VectorXd dq = q1-q0; - - Eigen::VectorXd A0 = q0; - Eigen::VectorXd A1 = v0 * ds; - Eigen::VectorXd A2 = a0 * (ds*ds) / 2.0; - Eigen::VectorXd C3 = ( 10.0*dq - (6.0*A1 + 1.5*(a0*ds*ds)) - (4.0*(v1*ds) - 0.5*(a1*ds*ds)) ); - Eigen::VectorXd C4 = (-15.0*dq + (8.0*A1 + 1.5*(a0*ds*ds)) + (7.0*(v1*ds) - 1.0*(a1*ds*ds)) ); - Eigen::VectorXd C5 = ( 6.0*dq - (3.0*A1 + 0.5*(a0*ds*ds)) - (3.0*(v1*ds) - 0.5*(a1*ds*ds)) ); - - toppra::Matrix seg(6, DoF); - seg.row(0)=(C5 / std::pow(ds, 5)).transpose(); - seg.row(1)=(C4 / std::pow(ds, 4)).transpose(); - seg.row(2)=(C3 / std::pow(ds, 3)).transpose(); - seg.row(3)=(a0 / 2.0).transpose(); - seg.row(4)=v0.transpose(); - seg.row(5)=A0.transpose(); - segs.emplace_back(std::move(seg)); - } - return std::make_shared(segs, std::vector(S.begin(), S.end())); - } - - std::vector ToppraJointTrajectoryPlanner::sampleTrajectory(const TrajPtr &traj, double dt) { - std::vector out; - if (!traj) return out; - - auto I = traj->timeInterval(); - const double t0 = I[0]; - const double t1 = I[1]; - if (!(t1 > t0)) return out; - - // 2) 生成时间序列(含端点,考虑浮点误差) - constexpr double EPS = 1e-12; - std::vector ts; - ts.reserve(static_cast(std::max(2.0, std::ceil((t1 - t0) / dt) + 1.0))); - - // 起点 - ts.push_back(t0); - - // 中间等间隔点 - for (double t = t0 + dt; t <= t1 - EPS; t += dt) { - // 防守式:避免因累积误差越过 t1 - ts.push_back((t > t1) ? t1 : t); - } - - // 终点(若未加入) - if (ts.empty() || std::fabs(ts.back() - t1) > EPS) { - ts.push_back(t1); - } else { - // 若最后一个点因误差“很接近 t1”,直接覆盖为 t1 - ts.back() = t1; - } - - // 3) 采样 - out.reserve(ts.size()); - for (double t: ts) { - TrajSample s; - s.t = t; - s.q = traj->q(t); - s.qd = traj->qd(t); - s.qdd = traj->qdd(t); - out.emplace_back(std::move(s)); - } - return out; - } - - - bool ToppraJointTrajectoryPlanner::writeTrajectoryCsv(const std::string &filename, const std::vector &samples) { - if (samples.empty()) return false; - - const int dof = static_cast(samples.front().q.size()); - std::ofstream ofs(filename); - if (!ofs) return false; - - ofs.setf(std::ios::fixed); - ofs << std::setprecision(10); - - // 表头 - ofs << "t"; - for (int j=1;j<=dof;++j) ofs << ",q" << j; - for (int j=1;j<=dof;++j) ofs << ",qd" << j; - for (int j=1;j<=dof;++j) ofs << ",qdd" << j; - ofs << "\n"; - - // 内容 - for (const auto& s : samples) { - ofs << s.t; - for (int j=0;j -#include -#include -#include -#include -#include -#include - -#include - -#include "joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" - -namespace cmvr { -namespace { - -constexpr std::size_t kDof = 7; -constexpr double kVelocityLimit = 0.15; -constexpr double kAccelerationLimit = 0.3; -constexpr double kSamplePeriodS = 0.002; - -std::vector> makeSmoothWaypoints(const std::size_t count) -{ - constexpr double kPi = 3.14159265358979323846; - std::vector> waypoints; - waypoints.reserve(count); - for (std::size_t i = 0; i < count; ++i) { - const double s = static_cast(i) / - static_cast(count - 1); - std::vector q(kDof, 0.0); - q[0] = 0.40 * s + 0.03 * std::sin(2.0 * kPi * s); - q[1] = -0.25 * s + 0.04 * std::sin(kPi * s); - q[2] = 0.20 * s * s; - q[3] = 0.30 * std::sin(0.5 * kPi * s); - q[4] = -0.12 * s + 0.02 * std::sin(3.0 * kPi * s); - q[5] = 0.15 * s; - q[6] = -0.08 * std::sin(kPi * s); - waypoints.push_back(std::move(q)); - } - return waypoints; -} - -double maxAbs(const Eigen::VectorXd& value) -{ - double result = 0.0; - for (Eigen::Index i = 0; i < value.size(); ++i) { - result = std::max(result, std::abs(value[i])); - } - return result; -} - -double positionError(const Eigen::VectorXd& actual, - const std::vector& expected) -{ - if (actual.size() != static_cast(expected.size())) { - return std::numeric_limits::infinity(); - } - double squared_error = 0.0; - for (Eigen::Index i = 0; i < actual.size(); ++i) { - const double error = actual[i] - expected[static_cast(i)]; - squared_error += error * error; - } - return std::sqrt(squared_error); -} - -struct PlanMetrics { - bool success{false}; - double planning_ms{0.0}; - double duration_s{0.0}; - double max_velocity{0.0}; - double max_acceleration{0.0}; - double max_waypoint_error{0.0}; - double start_error{0.0}; - double end_error{0.0}; - std::size_t sample_count{0}; -}; - -PlanMetrics planAndMeasure(const std::vector>& waypoints, - const PathType path_type = PathType::Linear) -{ - PlanMetrics metrics; - ToppraJointTrajectoryPlanner planner(path_type); - planner.setSymmetricLimits( - std::vector(kDof, kVelocityLimit), - std::vector(kDof, kAccelerationLimit)); - planner.setGridSizes(150, 300); - - TrajPtr trajectory; - const auto start = std::chrono::steady_clock::now(); - metrics.success = planner.plan(waypoints, trajectory); - metrics.planning_ms = std::chrono::duration( - std::chrono::steady_clock::now() - start).count(); - if (!metrics.success || !trajectory) { - return metrics; - } - - const auto interval = trajectory->timeInterval(); - metrics.duration_s = interval[1] - interval[0]; - const auto samples = planner.sampleTrajectory(trajectory, kSamplePeriodS); - metrics.sample_count = samples.size(); - if (samples.empty()) { - metrics.success = false; - return metrics; - } - metrics.start_error = positionError(samples.front().q, waypoints.front()); - metrics.end_error = positionError(samples.back().q, waypoints.back()); - - for (const auto& sample : samples) { - if (!std::isfinite(sample.t) || !sample.q.allFinite() || - !sample.qd.allFinite() || !sample.qdd.allFinite()) { - metrics.success = false; - return metrics; - } - metrics.max_velocity = std::max(metrics.max_velocity, maxAbs(sample.qd)); - metrics.max_acceleration = std::max( - metrics.max_acceleration, maxAbs(sample.qdd)); - } - - std::size_t sample_index = 0; - for (const auto& waypoint : waypoints) { - while (sample_index + 1 < samples.size() && - positionError(samples[sample_index + 1].q, waypoint) <= - positionError(samples[sample_index].q, waypoint)) { - ++sample_index; - } - metrics.max_waypoint_error = std::max( - metrics.max_waypoint_error, - positionError(samples[sample_index].q, waypoint)); - } - return metrics; -} - -const char* pathTypeName(const PathType path_type) -{ - switch (path_type) { - case PathType::Linear: return "Linear"; - case PathType::CubicHermite: return "CubicHermite"; - case PathType::Quintic: return "Quintic"; - case PathType::Natural: return "Natural"; - } - return "Unknown"; -} - -void printMetrics(const std::size_t waypoint_count, const PlanMetrics& metrics) -{ - std::cout << "[ToppraMultiWaypointTest] waypoints=" << waypoint_count - << ", success=" << metrics.success - << ", planning_ms=" << metrics.planning_ms - << ", duration_s=" << metrics.duration_s - << ", samples=" << metrics.sample_count - << ", max_qd=" << metrics.max_velocity - << ", max_qdd=" << metrics.max_acceleration - << ", max_waypoint_error=" << metrics.max_waypoint_error - << ", start_error=" << metrics.start_error - << ", end_error=" << metrics.end_error - << std::endl; -} - -TEST(ToppraMultiWaypointTest, SmoothSevenDofPathScalesToThousandsOfWaypoints) -{ - double reference_duration_s = 0.0; - for (const std::size_t count : {10U, 100U, 300U, 1000U, 3000U}) { - const auto metrics = planAndMeasure(makeSmoothWaypoints(count)); - printMetrics(count, metrics); - ASSERT_TRUE(metrics.success) << "waypoint_count=" << count; - EXPECT_GT(metrics.duration_s, 0.0) << "waypoint_count=" << count; - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6) - << "waypoint_count=" << count; - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5) - << "waypoint_count=" << count; - EXPECT_LT(metrics.max_waypoint_error, 0.002) - << "waypoint_count=" << count; - if (reference_duration_s == 0.0) { - reference_duration_s = metrics.duration_s; - } else { - EXPECT_NEAR(metrics.duration_s, reference_duration_s, - reference_duration_s * 0.10) - << "waypoint_count=" << count; - } - } -} - -TEST(ToppraMultiWaypointTest, RepeatedWaypointsRemainPlannable) -{ - const auto smooth = makeSmoothWaypoints(300); - std::vector> repeated; - repeated.reserve(smooth.size() * 2); - for (const auto& waypoint : smooth) { - repeated.push_back(waypoint); - repeated.push_back(waypoint); - } - - const auto metrics = planAndMeasure(repeated); - printMetrics(repeated.size(), metrics); - EXPECT_TRUE(metrics.success); - if (metrics.success) { - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6); - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5); - EXPECT_LT(metrics.max_waypoint_error, 0.002); - } -} - -TEST(ToppraMultiWaypointTest, CompareInterpolationModesAtThreeHundredWaypoints) -{ - const auto waypoints = makeSmoothWaypoints(300); - for (const auto path_type : { - PathType::CubicHermite, - PathType::Quintic, - PathType::Natural}) { - const auto metrics = planAndMeasure(waypoints, path_type); - std::cout << "[ToppraMultiWaypointTest] path_type=" - << pathTypeName(path_type) << std::endl; - printMetrics(waypoints.size(), metrics); - EXPECT_TRUE(metrics.success) << pathTypeName(path_type); - if (metrics.success) { - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6) - << pathTypeName(path_type); - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5) - << pathTypeName(path_type); - EXPECT_LT(metrics.max_waypoint_error, 0.002) - << pathTypeName(path_type); - EXPECT_LT(metrics.start_error, 1e-9) << pathTypeName(path_type); - EXPECT_LT(metrics.end_error, 1e-9) << pathTypeName(path_type); - } - } -} - -} // namespace -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h deleted file mode 100644 index 551abaa0..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h +++ /dev/null @@ -1,100 +0,0 @@ -// -// Created by lgv on 2026/3/10. -// - -#pragma once - -#include "s_curve_velocity_planner.h" - -#include -#include - -namespace cmvr -{ - -struct SCurvePositionPlannerState -{ - double position; - double velocity; - double acceleration; - double jerk; - double target_position; - bool is_moving; - - SCurvePositionPlannerState() - : position(0.0) - , velocity(0.0) - , acceleration(0.0) - , jerk(0.0) - , target_position(0.0) - , is_moving(false) - {} -}; - -/** - * @brief 单轴位置跟踪规划器 - * - * 结构: - * - 外环:position_error -> desired_velocity - * - 内环:SCurveVelocityPlanner1D 负责 jerk-limited 速度规划 - * - * 这个类用于高频变化目标的位置跟踪,不承担严格点到点 profile 语义。 - */ -class SCurvePositionPlanner1D -{ -public: - SCurvePositionPlanner1D(double max_velocity = 3.0, - double max_acceleration = 10.0, - double max_jerk = 50.0); - - void setConstraints(double max_velocity, double max_acceleration, double max_jerk); - void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const; - - void setPositionGain(double position_gain); - double getPositionGain() const { return position_gain_; } - - void initialize(double position, double velocity = 0.0, double acceleration = 0.0); - void reset(); - - void setTarget(double target_position); - double update(double dt); - - const SCurvePositionPlannerState& getState() const { return state_; } - double getPosition() const { return state_.position; } - double getVelocity() const { return state_.velocity; } - double getAcceleration() const { return state_.acceleration; } - double getJerk() const { return state_.jerk; } - double getTargetPosition() const { return state_.target_position; } - bool isMoving() const { return state_.is_moving; } - -private: - double max_velocity_; - double max_acceleration_; - double max_jerk_; - - SCurvePositionPlannerState state_; - SCurveVelocityPlanner1D velocity_planner_; - double position_gain_; - - static constexpr double EPSILON = 1e-9; - static constexpr double VELOCITY_THRESHOLD = 1e-6; - static constexpr double ACCELERATION_THRESHOLD = 1e-6; - static constexpr double POSITION_THRESHOLD = 1e-7; - - double computeDesiredVelocity(double position_error) const; - double computePlannerStoppingDistance(double velocity, double acceleration) 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/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h deleted file mode 100644 index f9e59774..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h +++ /dev/null @@ -1,240 +0,0 @@ -// -// Created by lgv on 2026/3/9. -// - -#pragma once - -#include -#include -#include - -namespace cmvr -{ - -/** - * @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 SCurveVelocityProfile -{ - double t1; - double t2; - double t3; - - double total_time; - - double j1; - double j2; - double j3; - - double v0; - double a0; - double vf; - - bool valid; - - SCurveVelocityProfile() - : 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 曲线速度规划器状态 - */ -struct SCurveVelocityPlannerState -{ - double velocity; - double acceleration; - double jerk; - - double target_velocity; - - double elapsed_time; - bool has_active_profile; - bool is_moving; - - SCurveVelocityPlannerState() - : velocity(0.0) - , acceleration(0.0) - , jerk(0.0) - , target_velocity(0.0) - , elapsed_time(0.0) - , has_active_profile(false) - , is_moving(false) - {} -}; - -/** - * @brief 单轴速度型 S 曲线规划器 - * - * 语义: - * - setTargetVelocity(v): 设置新目标并重规划 - * - update(dt): 只采样当前 active profile - * - overwriteState(v,a): 仅覆盖当前状态并清掉旧 profile - * - synchronizeAndReplan(v,a): 用测量状态同步,并按当前目标重规划 - * - * 数学目标: - * - 从任意 (v0, a0) 连续规划到 (vf, 0) - * - 满足 |v| <= v_max, |a| <= a_max, |j| <= j_max - */ -class SCurveVelocityPlanner1D -{ -public: - SCurveVelocityPlanner1D(double max_velocity = 1.0, - double max_acceleration = 1.0, - double max_jerk = 5.0); - - void setConstraints(double max_velocity, double max_acceleration, double max_jerk); - void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const; - - /** - * @brief 设置目标变化阈值 - * - * 目标变化量小于该阈值时,不触发重规划。 - */ - void setTargetReplanThreshold(double threshold); - - /** - * @brief 设置同步反馈时的重规划阈值 - * - * 测量速度与当前 profile 采样状态的偏差小于该阈值时, - * synchronizeAndReplan() 只对齐当前状态,不打断现有 profile。 - */ - void setSynchronizeReplanThreshold(double threshold); - - void initialize(double velocity = 0.0, double acceleration = 0.0); - void reset(); - - /** - * @brief 仅覆盖当前状态,并清掉旧 profile - * - * 注意: - * - 这个接口不会自动重规划 - * - 用于初始化、调试、或显式中断旧轨迹 - */ - void overwriteState(double velocity, - double acceleration = 0.0, - bool keep_target_velocity = true); - - /** - * @brief 用测量状态同步,并按当前目标重新规划 - * - * 这是闭环场景真正该用的接口。 - */ - void synchronizeAndReplan(double velocity, - double acceleration = 0.0); - - /** - * @brief 设置目标速度,并立即重规划 - */ - void setTargetVelocity(double target_velocity); - - /** - * @brief 平滑停下 - */ - void stop() { setTargetVelocity(0.0); } - - /** - * @brief 更新一步(只采样) - * @param dt 时间步长 - * @return 当前采样后的速度 - */ - double update(double dt); - - /** - * @brief 计算单次速度切换剖面 - */ - SCurveVelocityProfile calculateProfile(double start_velocity, - double end_velocity, - double start_acceleration = 0.0) const; - - /** - * @brief 给定剖面下,获取时刻 t 的速度 - */ - double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 给定剖面下,获取时刻 t 的加速度 - */ - double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 给定剖面下,获取时刻 t 的 jerk - */ - double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 按固定时间间隔生成轨迹点 - */ - void generateTrajectory(const SCurveVelocityProfile& profile, double dt, - std::vector& velocities, - std::vector& accelerations, - std::vector& jerks) const; - - const SCurveVelocityPlannerState& getState() const { return state_; } - const SCurveVelocityProfile& getActiveProfile() const { return active_profile_; } - - double getVelocity() const { return state_.velocity; } - double getAcceleration() const { return state_.acceleration; } - double getJerk() const { return state_.jerk; } - double getTargetVelocity() const { return state_.target_velocity; } - bool hasActiveProfile() const { return state_.has_active_profile; } - bool isMoving() const { return state_.is_moving; } - -private: - double max_velocity_; - double max_acceleration_; - double max_jerk_; - - double target_replan_threshold_; - double synchronize_replan_threshold_; - - SCurveVelocityPlannerState state_; - SCurveVelocityProfile active_profile_; - - static constexpr double EPSILON = 1e-9; - static constexpr double VELOCITY_THRESHOLD = 1e-6; - static constexpr double ACCELERATION_THRESHOLD = 1e-6; - static constexpr double DEFAULT_TARGET_REPLAN_THRESHOLD = 1e-9; - static constexpr double DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD = 5e-2; - -private: - void updateIsMovingFlag(); - - /** - * @brief 判断 profile 是否满足速度上限 - */ - bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const; - - /** - * @brief 计算完整剖面终点状态 - */ - void integrateWholeProfile(const SCurveVelocityProfile& 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/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp deleted file mode 100644 index b379f059..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp +++ /dev/null @@ -1,191 +0,0 @@ -// -// Created by lgv on 2026/3/10. -// - -#include "../include/s_curve_position_planner.h" - -#include -#include - -namespace cmvr -{ - -SCurvePositionPlanner1D::SCurvePositionPlanner1D(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)) - , velocity_planner_(max_velocity_, max_acceleration_, max_jerk_) - , position_gain_(1.0) -{ - velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_)); - reset(); -} - -void SCurvePositionPlanner1D::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); - velocity_planner_.setConstraints(max_velocity_, max_acceleration_, max_jerk_); - velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_)); -} - -void SCurvePositionPlanner1D::getConstraints(double& max_velocity, - double& max_acceleration, - double& max_jerk) const -{ - max_velocity = max_velocity_; - max_acceleration = max_acceleration_; - max_jerk = max_jerk_; -} - -void SCurvePositionPlanner1D::setPositionGain(double position_gain) -{ - position_gain_ = std::max(0.0, position_gain); -} - -void SCurvePositionPlanner1D::initialize(double position, double velocity, double acceleration) -{ - state_.position = position; - velocity_planner_.initialize(velocity, acceleration); - state_.velocity = velocity_planner_.getVelocity(); - state_.acceleration = velocity_planner_.getAcceleration(); - state_.jerk = 0.0; - state_.target_position = position; - state_.is_moving = false; -} - -void SCurvePositionPlanner1D::reset() -{ - state_ = SCurvePositionPlannerState(); - velocity_planner_.reset(); -} - -void SCurvePositionPlanner1D::setTarget(double target_position) -{ - state_.target_position = target_position; -} - -double SCurvePositionPlanner1D::update(double dt) -{ - if (dt <= 0.0 || dt > 0.1) { - return state_.position; - } - - const double position_error = state_.target_position - state_.position; - if (std::abs(position_error) < POSITION_THRESHOLD && - std::abs(velocity_planner_.getVelocity()) < VELOCITY_THRESHOLD && - std::abs(velocity_planner_.getAcceleration()) < ACCELERATION_THRESHOLD) { - velocity_planner_.overwriteState(0.0, 0.0, false); - state_.position = state_.target_position; - state_.velocity = 0.0; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.is_moving = false; - return state_.position; - } - - velocity_planner_.setTargetVelocity(computeDesiredVelocity(position_error)); - - const double old_velocity = velocity_planner_.getVelocity(); - const double new_velocity = velocity_planner_.update(dt); - - state_.velocity = new_velocity; - state_.acceleration = velocity_planner_.getAcceleration(); - state_.jerk = velocity_planner_.getJerk(); - state_.position += 0.5 * (old_velocity + new_velocity) * dt; - - const double updated_error = state_.target_position - state_.position; - if (std::abs(updated_error) < POSITION_THRESHOLD && - std::abs(state_.velocity) < VELOCITY_THRESHOLD && - std::abs(state_.acceleration) < ACCELERATION_THRESHOLD) { - velocity_planner_.overwriteState(0.0, 0.0, false); - state_.position = state_.target_position; - state_.velocity = 0.0; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.is_moving = false; - return state_.position; - } - - state_.is_moving = velocity_planner_.isMoving() || - std::abs(updated_error) > POSITION_THRESHOLD; - return state_.position; -} - -double SCurvePositionPlanner1D::computeDesiredVelocity(double position_error) const -{ - if (std::abs(position_error) <= POSITION_THRESHOLD) { - return 0.0; - } - - const double proportional_velocity = - clamp(position_gain_ * position_error, -max_velocity_, max_velocity_); - const double current_velocity = velocity_planner_.getVelocity(); - const double current_acceleration = velocity_planner_.getAcceleration(); - const double stopping_distance = - computePlannerStoppingDistance(current_velocity, current_acceleration); - - if (std::abs(current_velocity) > VELOCITY_THRESHOLD && - sign(current_velocity) != sign(position_error)) { - return 0.0; - } - - if (std::abs(current_velocity) > VELOCITY_THRESHOLD && - sign(current_velocity) == sign(position_error) && - std::abs(position_error) <= std::abs(stopping_distance) * 1.05) { - return 0.0; - } - - double low = 0.0; - double high = max_velocity_; - for (int i = 0; i < 40; ++i) { - const double mid = 0.5 * (low + high); - const double distance = - std::abs(computePlannerStoppingDistance(sign(position_error) * mid, 0.0)); - if (distance <= std::abs(position_error)) { - low = mid; - } else { - high = mid; - } - } - - return sign(position_error) * - std::min(std::abs(proportional_velocity), low); -} - -double SCurvePositionPlanner1D::computePlannerStoppingDistance(double velocity, - double acceleration) const -{ - if (std::abs(velocity) <= VELOCITY_THRESHOLD && - std::abs(acceleration) <= ACCELERATION_THRESHOLD) { - return 0.0; - } - - const auto profile = velocity_planner_.calculateProfile(velocity, 0.0, acceleration); - if (!profile.valid || profile.total_time <= EPSILON) { - return 0.0; - } - - const int steps = std::max(16, static_cast(std::ceil(profile.total_time / 0.002))); - const double dt = profile.total_time / static_cast(steps); - - double distance = 0.0; - double previous_time = 0.0; - double previous_velocity = velocity_planner_.getVelocityAtTime(profile, 0.0); - for (int i = 1; i <= steps; ++i) { - const double t = (i == steps) ? profile.total_time : i * dt; - const double current_velocity = velocity_planner_.getVelocityAtTime(profile, t); - distance += 0.5 * (previous_velocity + current_velocity) * (t - previous_time); - previous_time = t; - previous_velocity = current_velocity; - } - - return distance; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp deleted file mode 100644 index c058e673..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp +++ /dev/null @@ -1,578 +0,0 @@ -// -// Created by lgv on 2026/3/9. -// - -#include "../include/s_curve_velocity_planner.h" - -#include -#include - -namespace cmvr -{ - -SCurveVelocityPlanner1D::SCurveVelocityPlanner1D(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)) - , target_replan_threshold_(DEFAULT_TARGET_REPLAN_THRESHOLD) - , synchronize_replan_threshold_(DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD) -{ - reset(); -} - -void SCurveVelocityPlanner1D::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); - - state_.velocity = clamp(state_.velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(state_.acceleration, -max_acceleration_, max_acceleration_); - state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_); - - if (state_.has_active_profile) { - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON; - } - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::getConstraints(double& max_velocity, - double& max_acceleration, - double& max_jerk) const -{ - max_velocity = max_velocity_; - max_acceleration = max_acceleration_; - max_jerk = max_jerk_; -} - -void SCurveVelocityPlanner1D::setTargetReplanThreshold(double threshold) -{ - target_replan_threshold_ = std::max(0.0, threshold); -} - -void SCurveVelocityPlanner1D::setSynchronizeReplanThreshold(double threshold) -{ - synchronize_replan_threshold_ = std::max(0.0, threshold); -} - -void SCurveVelocityPlanner1D::initialize(double velocity, double acceleration) -{ - state_ = SCurveVelocityPlannerState(); - state_.velocity = clamp(velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_); - state_.jerk = 0.0; - state_.target_velocity = state_.velocity; - state_.elapsed_time = 0.0; - state_.has_active_profile = false; - - active_profile_ = SCurveVelocityProfile(); - active_profile_.v0 = state_.velocity; - active_profile_.a0 = state_.acceleration; - active_profile_.vf = state_.velocity; - active_profile_.valid = false; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::reset() -{ - state_ = SCurveVelocityPlannerState(); - active_profile_ = SCurveVelocityProfile(); -} - -void SCurveVelocityPlanner1D::overwriteState(double velocity, - double acceleration, - bool keep_target_velocity) -{ - state_.velocity = clamp(velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_); - state_.jerk = 0.0; - state_.elapsed_time = 0.0; - state_.has_active_profile = false; - - if (!keep_target_velocity) { - state_.target_velocity = state_.velocity; - } else { - state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_); - } - - active_profile_ = SCurveVelocityProfile(); - active_profile_.v0 = state_.velocity; - active_profile_.a0 = state_.acceleration; - active_profile_.vf = state_.target_velocity; - active_profile_.valid = false; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::synchronizeAndReplan(double velocity, - double acceleration) -{ - const double measured_velocity = clamp(velocity, -max_velocity_, max_velocity_); - double measured_acceleration = - clamp(acceleration, -max_acceleration_, max_acceleration_); - - // When the target is zero this planner is also used for Cartesian speed - // magnitudes. A magnitude is non-negative, while the finite-difference - // derivative of the measured magnitude is signed. Feeding a large negative - // measured acceleration into a signed 1-D velocity planner can generate a - // profile that crosses through zero and becomes negative before returning to - // zero. The twist limiter then multiplies that negative "norm" by the - // current direction, which reverses and amplifies the Cartesian command. - // - // For feedback resynchronization during a stop, synchronize the measured - // speed only and restart the stop profile with zero scalar acceleration. - // This avoids noise-sensitive stop replans and preserves a non-overshooting - // deceleration profile for speed-magnitude users. - if (std::abs(state_.target_velocity) <= VELOCITY_THRESHOLD) { - measured_acceleration = 0.0; - } - - if (!state_.has_active_profile && - std::abs(measured_velocity - state_.target_velocity) <= VELOCITY_THRESHOLD) { - state_.velocity = state_.target_velocity; - state_.acceleration = 0.0; - state_.jerk = 0.0; - updateIsMovingFlag(); - return; - } - - // 如果测量值已经基本落在当前采样状态上,就继续沿现有 profile 走。 - // 否则每拍都从同一目标重规划,会把已经进入的 jerk phase 反复打断。 - if (state_.has_active_profile && - std::abs(measured_velocity - state_.velocity) <= synchronize_replan_threshold_) { - state_.velocity = measured_velocity; - state_.acceleration = measured_acceleration; - state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time); - updateIsMovingFlag(); - return; - } - - state_.velocity = measured_velocity; - state_.acceleration = measured_acceleration; - state_.jerk = 0.0; - - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.total_time > EPSILON; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::setTargetVelocity(double target_velocity) -{ - const double new_target = clamp(target_velocity, -max_velocity_, max_velocity_); - - const bool same_target = - std::abs(new_target - state_.target_velocity) <= target_replan_threshold_; - - if (same_target && - state_.has_active_profile) { - return; - } - - if (same_target && - !state_.has_active_profile && - std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD && - std::abs(state_.acceleration) <= ACCELERATION_THRESHOLD) { - return; - } - - state_.target_velocity = new_target; - - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON; - - updateIsMovingFlag(); -} - -double SCurveVelocityPlanner1D::getVelocityAtTime(const SCurveVelocityProfile& 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 SCurveVelocityPlanner1D::getAccelerationAtTime(const SCurveVelocityProfile& 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 SCurveVelocityPlanner1D::getJerkAtTime(const SCurveVelocityProfile& 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 SCurveVelocityPlanner1D::integrateWholeProfile(const SCurveVelocityProfile& 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 SCurveVelocityPlanner1D::isVelocityLimitSatisfied(const SCurveVelocityProfile& 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; -} - -SCurveVelocityProfile SCurveVelocityPlanner1D::calculateProfile(double start_velocity, - double end_velocity, - double start_acceleration) const -{ - SCurveVelocityProfile 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; - } - - SCurveVelocityProfile 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 SCurveVelocityPlanner1D::generateTrajectory(const SCurveVelocityProfile& 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); - } -} - -double SCurveVelocityPlanner1D::update(double dt) -{ - if (dt <= 0.0) { - return state_.velocity; - } - - if (!state_.has_active_profile || !active_profile_.valid) { - state_.jerk = 0.0; - updateIsMovingFlag(); - return state_.velocity; - } - - state_.elapsed_time += dt; - - if (state_.elapsed_time >= active_profile_.total_time) { - state_.elapsed_time = active_profile_.total_time; - state_.velocity = active_profile_.vf; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.has_active_profile = false; - updateIsMovingFlag(); - return state_.velocity; - } - - state_.velocity = getVelocityAtTime(active_profile_, state_.elapsed_time); - state_.acceleration = getAccelerationAtTime(active_profile_, state_.elapsed_time); - state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time); - - updateIsMovingFlag(); - return state_.velocity; -} - -void SCurveVelocityPlanner1D::updateIsMovingFlag() -{ - state_.is_moving = - state_.has_active_profile || - std::abs(state_.velocity) > VELOCITY_THRESHOLD || - std::abs(state_.target_velocity) > VELOCITY_THRESHOLD || - std::abs(state_.acceleration) > ACCELERATION_THRESHOLD; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp deleted file mode 100644 index 12ba5e38..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include - -#include - -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h" - -namespace cmvr { -namespace { - -void finishActiveProfile(SCurveVelocityPlanner1D& planner, double dt) -{ - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - planner.update(dt); - } - ASSERT_FALSE(planner.hasActiveProfile()); -} - -TEST(SCurveVelocityPlannerStopTest, FeedbackResyncDoesNotReverseSpeedMagnitude) -{ - SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0); - constexpr double kDt = 0.001; - constexpr double kInitialSpeed = 0.04; - - planner.initialize(kInitialSpeed, 0.0); - planner.setTargetVelocity(0.0); - finishActiveProfile(planner, kDt); - - // Reproduce the speedL stop feedback case: the command profile has already - // reached zero, but the measured TCP still has residual speed. A 1 kHz - // finite difference may report a large negative scalar acceleration. - planner.synchronizeAndReplan(kInitialSpeed, -3.0); - - double max_speed = planner.getVelocity(); - double min_speed = planner.getVelocity(); - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - const double speed = planner.update(kDt); - max_speed = std::max(max_speed, speed); - min_speed = std::min(min_speed, speed); - } - - EXPECT_GE(min_speed, -1e-9); - EXPECT_LE(max_speed, kInitialSpeed + 1e-9); - EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9); -} - -TEST(SCurveVelocityPlannerStopTest, LargerMeasuredDecelerationDoesNotIncreaseStopSpeed) -{ - constexpr double kDt = 0.001; - constexpr double kInitialSpeed = 0.04; - const double measured_accelerations[] = {-0.5, -1.0, -2.0, -3.0}; - - for (const double measured_acceleration : measured_accelerations) { - SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0); - planner.initialize(kInitialSpeed, 0.0); - planner.setTargetVelocity(0.0); - finishActiveProfile(planner, kDt); - - planner.synchronizeAndReplan(kInitialSpeed, measured_acceleration); - - double max_speed = planner.getVelocity(); - double min_speed = planner.getVelocity(); - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - const double speed = planner.update(kDt); - max_speed = std::max(max_speed, speed); - min_speed = std::min(min_speed, speed); - } - - EXPECT_GE(min_speed, -1e-9) << "measured_acceleration=" << measured_acceleration; - EXPECT_LE(max_speed, kInitialSpeed + 1e-9) - << "measured_acceleration=" << measured_acceleration; - EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9) - << "measured_acceleration=" << measured_acceleration; - } -} - -} // namespace -} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/CMakeLists.txt b/cmvr-es/algorithms/planner/CMakeLists.txt new file mode 100644 index 00000000..1216b7a4 --- /dev/null +++ b/cmvr-es/algorithms/planner/CMakeLists.txt @@ -0,0 +1,49 @@ +add_library(base_motion SHARED + cartesian/s_curve/src/s_curve_planner.cpp) +target_include_directories(base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(base_motion PUBLIC + cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common) +add_library(cmvr_es::base_motion ALIAS base_motion) +install(TARGETS base_motion LIBRARY DESTINATION lib) + +add_library(arm_motion SHARED + cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp + cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp) +target_include_directories(arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(arm_motion PUBLIC + cmvr_es::ik_solver cmvr_es::base_motion cmvr_es::curves) +add_library(cmvr_es::arm_motion ALIAS arm_motion) +add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion) +install(TARGETS 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::base_motion gtest gtest_main) + +add_executable(pinocchio_speedl_limits_test + cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp) +target_compile_definitions(pinocchio_speedl_limits_test PRIVATE + CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(pinocchio_speedl_limits_test PRIVATE + cmvr_es::algorithms::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..fb4bafb3 --- /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::SCurvePlanner 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..4002b8a7 --- /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::SCurve curve(velocity, acceleration, jerk); + const cmvr::SCurveProfile 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..18c99e37 --- /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::SCurvePlanner 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 = SCurve(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 ? CartesianFrame::Tool : CartesianFrame::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..2d247248 --- /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 CartesianFrame +{ + Base = 0, + Tool = 1 +}; + +/** + * @brief 基于 SCurve 的六维末端在线速度规划器。 + * + * initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。 + * 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。 + * 非连续模式与角速度近反向时,先停稳再反向。 + * 传入零目标平滑停止;相同目标会继续当前曲线,不会每拍重规划。 + * 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。 + * 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。 + */ +class SCurvePlanner +{ +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, CartesianFrame 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; + + // 保存一维速度曲线的运行状态;数学计算由 SCurve 完成。 + 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(); + + SCurve curve_{1.0, 1.0, 5.0}; + Sample state_; + SCurveVelocityProfile 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..83b7453a --- /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::SCurvePlanner& 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..ebb2fd75 --- /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) +{ + // SCurve'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 SCurvePlanner::VelocityState::limits() const +{ + std::array result; + curve_.getConstraints(result[0], result[1], result[2]); + return result; +} + +void SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::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_ = SCurveVelocityProfile(); +} + +void SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::VelocityState::isSettled() const +{ + return !state_.has_active_profile && + std::abs(state_.velocity) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0; +} + +bool SCurvePlanner::VelocityState::isMoving() const +{ + return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD; +} + +std::pair +SCurvePlanner::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 SCurvePlanner::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; +} + +SCurvePlanner::DirectionProfile SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk); +} + +void SCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk); +} + +void SCurvePlanner::setLinearTargetReplanThreshold(double threshold) +{ + linear_velocity_.setTargetReplanThreshold(threshold); +} + +void SCurvePlanner::setAngularTargetReplanThreshold(double threshold) +{ + angular_velocity_.setTargetReplanThreshold(threshold); +} + +void SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::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 SCurvePlanner::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; +} + +SCurvePlanner::Twist +SCurvePlanner::plan(const Twist& target_twist, CartesianFrame 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 != CartesianFrame::Base && frame != CartesianFrame::Tool) || + !target_twist.allFinite() || + (frame == CartesianFrame::Tool && !base_R_tool.allFinite())) { + throw std::invalid_argument("invalid S-curve target, frame or tool rotation"); + } + Twist target_base = target_twist; + if (frame == CartesianFrame::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 SCurvePlanner::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..29013d9f --- /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 = SCurvePlanner::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) { + SCurvePlanner 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), CartesianFrame::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), CartesianFrame::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(SCurvePlannerReversal, 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(SCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 1, 4); + planner.initialize(y(.02)); + for (int i = 0; i < 100; ++i) planner.plan(y(-.02), CartesianFrame::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), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003); +} +TEST(SCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) { + for (double v : {.08, -.08}) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + planner.initialize(y(v)); + for (int i = 0; i < 1000; ++i) { + EXPECT_GE(planner.plan(Twist::Zero(), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12); + } + EXPECT_FALSE(planner.isMoving()); + EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12); + } +} +TEST(SCurvePlannerReversal, 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); + SCurvePlanner 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, CartesianFrame::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, CartesianFrame::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, CartesianFrame::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, CartesianFrame::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(SCurvePlannerReversal, 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); + SCurvePlanner 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, CartesianFrame::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(), CartesianFrame::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(SCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) { + for (const int reverse_ticks : {150, 250, 500}) { + SCOPED_TRACE(reverse_ticks); + SCurvePlanner reference; + reference.setLinearConstraints(1, 3, 10); + reference.initialize(y(.08)); + for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), CartesianFrame::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), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual = streaming.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_NEAR((actual - expected).norm(), 0, 1e-9); + EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6); + } + } +} + +TEST(SCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) { + SCurvePlanner 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, CartesianFrame::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(SCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + for (int i = 0; i < 100; ++i) { + const double period = i % 2 ? .0005 : .001; + planner.plan(y(.08), CartesianFrame::Base, period, Eigen::Matrix3d::Identity()); + EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7); + } +} + +TEST(SCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) { + SCurvePlanner actual; + actual.setLinearConstraints(.05, 1e-6, .001); + actual.initialize(y(.0499995)); + actual.plan(y(.05), CartesianFrame::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), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const Twist b = reference.plan(y(.05), CartesianFrame::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(SCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) { + SCurvePlanner 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, CartesianFrame::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, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual_twist = actual.plan(target, CartesianFrame::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, CartesianFrame::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, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); }); + } + Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity(); + invalid_rotation(1, 2) = invalid; + expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::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, CartesianFrame::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/motion_planner/arm_motion/joint_motion/joint_motion_planner.h b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h similarity index 70% rename from cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h rename to cmvr-es/algorithms/smoother/joint_trajectory_validation.h index a2f77c51..f0dbffdc 100644 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h +++ b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h @@ -1,5 +1,4 @@ -#ifndef CMVR_ES_JOINT_MOTION_PLANNER_H -#define CMVR_ES_JOINT_MOTION_PLANNER_H +#pragma once #include #include @@ -10,46 +9,24 @@ namespace cmvr::device { -class JointMotionPlanner { -public: - virtual ~JointMotionPlanner() = default; - - virtual bool init() = 0; - - virtual bool planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - double speed_scaling, - JointTrajectory& trajectory) = 0; - - virtual bool planReplay(const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) = 0; - - bool validateJointTrajectory(const JointTrajectory& trajectory, - std::size_t expected_dof, - const MotionOptions& limits) const; -}; - -inline bool JointMotionPlanner::validateJointTrajectory( +inline bool validateJointTrajectory( const JointTrajectory& trajectory, const std::size_t expected_dof, - const MotionOptions& limits) const + const MotionOptions& limits) { if (trajectory.size() < 2 || expected_dof == 0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory must contain at least " + 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) << "[JointMotionPlanner] velocity or acceleration limit is invalid"; + 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) << "[JointMotionPlanner] joint velocity limit count does not match DOF"; + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] joint velocity limit count does not match DOF"; return false; } @@ -68,7 +45,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( if (!std::isfinite(point.time_s) || point.position.size() != expected_dof || point.velocity.size() != expected_dof) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid trajectory point at index=" << i; + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid trajectory point at index=" << i; return false; } @@ -76,7 +53,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( if (i > 0) { dt = point.time_s - trajectory[i - 1].time_s; if (!std::isfinite(dt) || dt <= 0.0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory time is not increasing at index=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory time is not increasing at index=" << i; return false; } @@ -85,7 +62,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( for (std::size_t joint = 0; joint < expected_dof; ++joint) { if (!std::isfinite(point.position[joint]) || !std::isfinite(point.velocity[joint])) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] non-finite trajectory value at point=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] non-finite trajectory value at point=" << i << ", joint=" << joint; return false; } @@ -95,13 +72,13 @@ inline bool JointMotionPlanner::validateJointTrajectory( ? limits.velocity : limits.joint_velocity_limits[joint]; if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid velocity limit for joint=" + 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) << "[JointMotionPlanner] velocity limit exceeded at point=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity limit exceeded at point=" << i << ", joint=" << joint << ", actual=" << velocity << ", limit=" << velocity_limit; @@ -119,20 +96,22 @@ inline bool JointMotionPlanner::validateJointTrajectory( maximum_acceleration, std::abs(acceleration)); if (std::abs(acceleration) > limits.acceleration + kAccelerationTolerance) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] acceleration limit exceeded at point=" + 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]) / dt); + previous_position_velocity[joint]) / midpoint_dt); maximum_jerk = std::max( maximum_jerk, - std::abs(acceleration - previous_acceleration[joint]) / dt); + std::abs(acceleration - previous_acceleration[joint]) / midpoint_dt); } previous_position_velocity[joint] = position_velocity; previous_acceleration[joint] = acceleration; @@ -140,7 +119,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( } } - CMVR_LOG(INFO) << "[JointMotionPlanner] trajectory validated" + CMVR_LOG(INFO) << "[JointTrajectoryValidation] trajectory validated" << ", points=" << trajectory.size() << ", max_velocity_rad_s=" << maximum_velocity << ", max_discrete_acceleration_rad_s2=" << maximum_acceleration @@ -151,6 +130,5 @@ inline bool JointMotionPlanner::validateJointTrajectory( return true; } -} // namespace cmvr::device -#endif // CMVR_ES_JOINT_MOTION_PLANNER_H +} // 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/math/transform_math.h b/cmvr-es/common/math/transform_math.h index 4f38ee62..ba590ee5 100644 --- a/cmvr-es/common/math/transform_math.h +++ b/cmvr-es/common/math/transform_math.h @@ -5,7 +5,6 @@ #include -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" #include "common/types/arm/arm_types.h" namespace cmvr::common::math { @@ -83,12 +82,6 @@ inline device::CartesianVelocity vectorToVelocity(const Eigen::Matrix #include +#include "environment/include/robot_model.h" + namespace cmvr::device { enum class ArmErrorCode { @@ -72,8 +74,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,32 +98,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 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); - } -}; - struct JointGroupState { std::vector position; std::vector velocity; @@ -139,6 +115,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; @@ -185,12 +164,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/arm.pb.txt b/cmvr-es/config/devices/arm/arm.pb.txt index 59b24597..f5540dc2 100644 --- a/cmvr-es/config/devices/arm/arm.pb.txt +++ b/cmvr-es/config/devices/arm/arm.pb.txt @@ -57,6 +57,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -66,12 +85,6 @@ arm { 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 - } } move_l { @@ -116,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 @@ -217,12 +238,23 @@ arm { } motion { - move_j { - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 } } @@ -268,9 +300,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt b/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt index f5c8d8f5..f16cdbe8 100644 --- a/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt +++ b/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt @@ -56,6 +56,26 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/gen2/collision/robot_collision.urdf" + ignored_pairs { first: "arm_link_5_2" second: "arm_link_7_2" } + ignored_pairs { first: "body_link" second: "arm_link_2_2" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -65,12 +85,6 @@ arm { 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 - } } move_l { @@ -115,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_mujoco.pb.txt b/cmvr-es/config/devices/arm/arm_mujoco.pb.txt index 6acc138b..d682461f 100644 --- a/cmvr-es/config/devices/arm/arm_mujoco.pb.txt +++ b/cmvr-es/config/devices/arm/arm_mujoco.pb.txt @@ -57,7 +57,28 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { + # 轨迹关节位置限位检查的数值容差,单位 rad;0 表示严格检查。 + joint_limit_tolerance_rad: 0.00001 # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 # MoveJ 完成时允许的最大关节位置误差,单位为弧度。 @@ -66,12 +87,6 @@ arm { 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 - } } move_l { @@ -116,9 +131,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt b/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt index 26b59ef0..ee8aa674 100644 --- a/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt +++ b/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt @@ -58,6 +58,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -67,12 +86,6 @@ arm { 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 - } } move_l { @@ -111,15 +124,23 @@ arm { pinocchio_cartesian_motion_planner { linear_velocity_max: 2.0 linear_acceleration_max: 15.0 - linear_jerk_max: 60.0 + linear_jerk_max: 500.0 angular_velocity_max: 1.0 angular_acceleration_max: 5.0 angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.005 diff --git a/cmvr-es/config/devices/arm/arm_qp.pb.txt b/cmvr-es/config/devices/arm/arm_qp.pb.txt index 6ad6d6d7..249a5493 100644 --- a/cmvr-es/config/devices/arm/arm_qp.pb.txt +++ b/cmvr-es/config/devices/arm/arm_qp.pb.txt @@ -58,6 +58,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -67,12 +86,6 @@ arm { 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 - } } move_l { @@ -111,15 +124,23 @@ arm { pinocchio_cartesian_motion_planner { linear_velocity_max: 0.8 linear_acceleration_max: 10.0 - linear_jerk_max: 60.0 + linear_jerk_max: 200.0 angular_velocity_max: 1.0 angular_acceleration_max: 5.0 angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt b/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt index ef6171c4..c5a1094e 100644 --- a/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt +++ b/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt @@ -57,6 +57,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -66,12 +85,6 @@ arm { 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 - } } move_l { @@ -116,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 @@ -217,12 +238,23 @@ arm { } motion { - move_j { - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 } } @@ -268,9 +300,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index 49439ea8..8889676b 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -6,42 +6,42 @@ device_manager { id: "mujoco_world" type: DEVICE_TYPE_MUJOCO_WORLD config_file: "devices/mujoco/right_arm_eye_to_hand_world.pb.txt" - enable: false + enable: true } devices { id: "right_arm_mujoco_motors" type: DEVICE_TYPE_MOTOR_SYSTEM config_file: "devices/motor/mujoco_motors.pb.txt" - enable: false + enable: true } devices { id: "mujoco_right_arm" type: DEVICE_TYPE_ROBOT_ARM config_file: "devices/arm/arm_mujoco_qp.pb.txt" - enable: false + enable: true } devices { id: "mujoco_viewer" type: DEVICE_TYPE_MUJOCO_VIEWER config_file: "devices/mujoco/mujoco_viewer.pb.txt" - enable: false + enable: true } devices { id: "mujoco_hand_cam" type: DEVICE_TYPE_CAMERA config_file: "devices/camera/camera.pb.txt" - enable: false + enable: true } devices { id: "mujoco_external_touch_cam" type: DEVICE_TYPE_CAMERA config_file: "devices/camera/camera.pb.txt" - enable: false + enable: true } devices { @@ -77,7 +77,7 @@ device_manager { id: "mujoco_zero_touch_dexhand" type: DEVICE_TYPE_DEXHAND config_file: "devices/dexhand/dexhand.pb.txt" - enable: false + enable: true } devices { diff --git a/cmvr-es/config/manager/task_manager.pb.txt b/cmvr-es/config/manager/task_manager.pb.txt index 387eebcc..1cc961c0 100644 --- a/cmvr-es/config/manager/task_manager.pb.txt +++ b/cmvr-es/config/manager/task_manager.pb.txt @@ -4,7 +4,7 @@ task_manager { type: TASK_TYPE_TOUCH_SCREEN run_mode: TASK_RUN_MODE_PERIODIC_STEP control_period_s: 0.001 - config_file: "tasks/touch_screen_task/touch_screen_task.pb.txt" + config_file: "tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt" enable: true } tasks { @@ -27,6 +27,6 @@ task_manager { type: TASK_TYPE_QUIC_EDGE run_mode: TASK_RUN_MODE_BLOCKING_SERVICE config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt" - enable: true + enable: false } } diff --git a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt index 69820cdd..ad8af832 100644 --- a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt +++ b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt @@ -14,8 +14,11 @@ touch_screen_task { } initialization { + # 开始前使用 MoveJ 回到初始关节位置。 before_start: false + # 正常完成后使用 MoveP 回到初始关节位置。 after_finish: true + after_failure: true joint_positions { joint_name: "R_SHOULDER_P" rad: -0.338732 } joint_positions { joint_name: "R_SHOULDER_R" rad: 1.265943 } joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.572396 } @@ -25,9 +28,9 @@ touch_screen_task { joint_positions { joint_name: "R_WRIST_R" rad: 0.1347 } velocity: 1.0 acceleration: 2.0 - # 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。 + # 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。 skip_position_tolerance_rad: 0.01 - # 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。 + # 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。 skip_velocity_tolerance_rad_s: 0.1 } @@ -88,15 +91,15 @@ touch_screen_task { stable_frames: 2 # 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。 timeout_s: 20.0 - # 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。 + # 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。 pause_when_reached: false } touch { speed_l { - twist_tool { x: 0.0 y: -0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } acceleration: 5.0 - linear_jerk: 10.0 + linear_jerk: 50.0 max_distance_m: 0.03 } tactile { @@ -109,9 +112,9 @@ touch_screen_task { } retract { - twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + twist_tool { x: 0.0 y: 0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } acceleration: 8.0 - linear_jerk: 40.0 # m/s^3,约束接触后的减速和连续换向。 + linear_jerk: 100.0 # m/s^3,约束接触后的减速和连续换向。 # TCP 后退目标距离,单位为米。 distance_m: 0.01 } diff --git a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt index 5bacf38f..c0f79928 100644 --- a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt +++ b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt @@ -14,8 +14,11 @@ touch_screen_task { } initialization { + # 开始前使用 MoveJ 回到初始关节位置。 before_start: true + # 正常完成后使用 MoveP 回到初始关节位置。 after_finish: true + after_failure: true joint_positions { joint_name: "R_SHOULDER_P" rad: -0.2423 } joint_positions { joint_name: "R_SHOULDER_R" rad: 1.2929 } joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.61 } @@ -25,9 +28,9 @@ touch_screen_task { joint_positions { joint_name: "R_WRIST_R" rad: -0.08 } velocity: 2.0 acceleration: 3.0 - # 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。 + # 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。 skip_position_tolerance_rad: 0.001 - # 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。 + # 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。 skip_velocity_tolerance_rad_s: 0.01 } @@ -51,6 +54,17 @@ touch_screen_task { } } + approach { + # MoveP 复用 alignment.target,position_offset_G 表达在屏幕 G 坐标系。 + enable: true + velocity: 0.65 # rad/s + acceleration: 1.7 # rad/s^2 + jerk: 30.0 # rad/s^3 + timeout_s: 10.0 + # TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。 + minimum_clearance_m: 0.01 + } + alignment { calibration { # TCP P 相对于屏幕 Hand Tag H 的目标姿态 @@ -97,15 +111,15 @@ touch_screen_task { stable_frames: 5 # 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。 timeout_s: 20.0 - # 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。 + # 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。 pause_when_reached: false } touch { speed_l { - twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } - acceleration: 6.0 - linear_jerk: 60.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。 + twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + acceleration: 10.0 + linear_jerk: 100.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。 max_distance_m: 0.02 } tactile { @@ -118,10 +132,10 @@ touch_screen_task { } retract { - twist_tool { x: 0.0 y: 0.06 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } - acceleration: 4.0 - linear_jerk: 60.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。 + twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + acceleration: 10.0 + linear_jerk: 500.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。 # TCP 后退目标距离,单位为米。 - distance_m: 0.05 + distance_m: 0.02 } } 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/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h b/cmvr-es/curves/s_curve/include/s_curve.h similarity index 59% rename from cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h rename to cmvr-es/curves/s_curve/include/s_curve.h index bc796ada..ee1d323d 100644 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h +++ b/cmvr-es/curves/s_curve/include/s_curve.h @@ -3,7 +3,7 @@ // /** * @file s_curve.h - * @brief 严格点到点位置 S 曲线轨迹生成器 + * @brief 位置与速度 S 曲线的数学计算 * * 实现标准 7 段式位置 S 曲线速度剖面: * 1. 加加速度上升段(加速度逐渐增大) @@ -14,7 +14,8 @@ * 6. 匀减速段 * 7. 加加速度上升段(减速度逐渐降到 0) * - * 本类只负责严格点到点 profile 规划与采样,不负责实时目标跟踪。 + * 同时支持三段式速度切换剖面。只负责剖面计算与按时间采样, + * 不保存运行状态,不负责实时目标更新、周期推进或反馈同步。 */ #pragma once @@ -70,7 +71,45 @@ struct SCurveProfile }; /** - * @brief 严格点到点位置 S 曲线规划器 + * @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 SCurveVelocityProfile +{ + double t1; + double t2; + double t3; + + double total_time; + + double j1; + double j2; + double j3; + + double v0; + double a0; + double vf; + + bool valid; + + SCurveVelocityProfile() + : 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 SCurve { @@ -81,9 +120,9 @@ public: * @param max_acceleration 最大加速度 (rad/s²) * @param max_jerk 最大加加速度 (rad/s³) */ - SCurve(double max_velocity = 3.0, - double max_acceleration = 10.0, - double max_jerk = 50.0); + SCurve(double max_velocity = 3.0, + double max_acceleration = 10.0, + double max_jerk = 50.0); /** * @brief 设置运动约束 @@ -103,8 +142,9 @@ public: * @param end_velocity 终止速度(默认 0) * @return 计算得到的剖面参数 */ - SCurveProfile calculateProfile(double start_position, double end_position, - double start_velocity = 0.0, double end_velocity = 0.0); + SCurveProfile calculatePositionProfile(double start_position, double end_position, + double start_velocity = 0.0, + double end_velocity = 0.0) const; /** * @brief 给定剖面下,获取时刻 t 的位置 @@ -151,6 +191,36 @@ public: std::vector& velocities, std::vector& accelerations) const; + /** + * @brief 计算单次速度切换剖面 + */ + SCurveVelocityProfile calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration = 0.0) const; + + /** + * @brief 给定剖面下,获取时刻 t 的速度 + */ + double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的加速度 + */ + double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的 jerk + */ + double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 按固定时间间隔生成轨迹点 + */ + void generateTrajectory(const SCurveVelocityProfile& profile, double dt, + std::vector& velocities, + std::vector& accelerations, + std::vector& jerks) const; + private: double max_velocity_; double max_acceleration_; @@ -158,10 +228,35 @@ private: static constexpr double EPSILON = 1e-9; static constexpr double VELOCITY_THRESHOLD = 1e-6; + static constexpr double ACCELERATION_THRESHOLD = 1e-6; double computeSegmentJerk(const SCurveProfile& profile, double t) const; void calculateShortProfile(SCurveProfile& profile) const; void calculateLongProfile(SCurveProfile& profile) const; + + /** + * @brief 判断 profile 是否满足速度上限 + */ + bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const; + + /** + * @brief 计算完整剖面终点状态 + */ + void integrateWholeProfile(const SCurveVelocityProfile& 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/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp b/cmvr-es/curves/s_curve/src/s_curve.cpp similarity index 62% rename from cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp rename to cmvr-es/curves/s_curve/src/s_curve.cpp index 720becab..3f34f338 100644 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp +++ b/cmvr-es/curves/s_curve/src/s_curve.cpp @@ -4,11 +4,11 @@ /** - * @file s_curve_generator.cpp - * @brief S 曲线轨迹生成器实现 + * @file s_curve.cpp + * @brief 位置与速度 S 曲线数学实现 */ -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h" +#include "curves/s_curve/include/s_curve.h" #include #include #include @@ -35,8 +35,8 @@ void SCurve::getConstraints(double& max_velocity, double& max_acceleration, doub max_jerk = max_jerk_; } -SCurveProfile SCurve::calculateProfile(double start_position, double end_position, - double start_velocity, double end_velocity) +SCurveProfile SCurve::calculatePositionProfile(double start_position, double end_position, + double start_velocity, double end_velocity) const { SCurveProfile profile; profile.j_max = max_jerk_; @@ -539,4 +539,336 @@ void SCurve::generateTrajectory(const SCurveProfile& profile, double dt, } } +double SCurve::getVelocityAtTime(const SCurveVelocityProfile& 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 SCurve::getAccelerationAtTime(const SCurveVelocityProfile& 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 SCurve::getJerkAtTime(const SCurveVelocityProfile& 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 SCurve::integrateWholeProfile(const SCurveVelocityProfile& 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 SCurve::isVelocityLimitSatisfied(const SCurveVelocityProfile& 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; +} + +SCurveVelocityProfile SCurve::calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration) const +{ + SCurveVelocityProfile 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; + } + + SCurveVelocityProfile 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 SCurve::generateTrajectory(const SCurveVelocityProfile& 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..fd43d15a 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}) @@ -10,7 +11,9 @@ target_link_libraries(motor_robot_arm PRIVATE cmvr_es::algorithms::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::mujoco_motor_driver glog @@ -19,11 +22,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..2789848c 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 规划。任务参数不能提高机械臂上限。 @@ -66,14 +89,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` 的旧项目库混用。 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 bd3f5c8d..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,7 +180,8 @@ private: mutable std::mutex mutex_; std::atomic busy_{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 f19328b2..f8cde2be 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,26 @@ #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/manager/include/motor_manager.h" +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" namespace cmvr::device { @@ -78,8 +84,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(); } } @@ -149,31 +155,47 @@ ArmState MotorRobotArm::getRobotState() const 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(); + auto solver = std::dynamic_pointer_cast(ik_solver_); + const auto& q = state.actual_joint_state.position; + const auto& qd = state.actual_joint_state.velocity; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (solver && q.size() == getDof() && qd.size() == getDof() && + std::all_of(qd.begin(), qd.end(), [](double v) { return std::isfinite(v); }) && + 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()); + 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); return state; } @@ -188,8 +210,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); @@ -203,7 +228,7 @@ SafetyMode MotorRobotArm::getSafetyMode() const if (protective_stopped_.load()) { return SafetyMode::ProtectiveStop; } - return SafetyMode::Normal; + return isFault() ? SafetyMode::Fault : SafetyMode::Normal; } Result MotorRobotArm::torqueOn() @@ -269,13 +294,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() @@ -283,14 +307,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) @@ -349,15 +527,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, @@ -460,17 +632,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 @@ -498,15 +672,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; } @@ -514,11 +689,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 @@ -533,14 +708,91 @@ 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_ || !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"); + } + 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); + } + 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_) { @@ -559,13 +811,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"); } @@ -583,13 +840,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. @@ -605,7 +855,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; } @@ -616,38 +866,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); @@ -655,8 +879,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(); } @@ -723,59 +983,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); } @@ -950,16 +1558,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 @@ -1018,28 +1626,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"); @@ -1048,15 +1658,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 { @@ -1070,9 +1684,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) { @@ -1080,7 +1697,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(); @@ -1101,7 +1718,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 @@ -1133,18 +1750,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) { @@ -1191,8 +1846,15 @@ bool MotorRobotArm::configureAlgorithms_() return false; } - joint_planner_ = JointMotionPlannerFactory::create(cfg_.motion().move_j()); - if (!joint_planner_) { + const auto& smoother_config = cfg_.motion().joint_trajectory_smoother(); + 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; } @@ -1201,6 +1863,18 @@ bool MotorRobotArm::configureAlgorithms_() 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; + } + + if (!configureJointPathPlanner_()) { + return false; + } + auto pinocchio_solver = std::dynamic_pointer_cast(ik_solver_); if (!pinocchio_solver) { return false; @@ -1208,32 +1882,33 @@ bool MotorRobotArm::configureAlgorithms_() const auto& move_l = cfg_.motion().move_l(); const auto& speed_l = cfg_.motion().speed_l(); - auto cartesian_motion = CartesianMotionPlannerFactory::create(move_l, speed_l, pinocchio_solver); - if (!cartesian_motion) { - return false; - } - 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())) { + auto cartesian_motion = CartesianMotionPlannerFactory::createMoveL(move_l, pinocchio_solver); + auto cartesian_velocity = CartesianMotionPlannerFactory::createSpeedL(speed_l, pinocchio_solver, getDof()); + if (!cartesian_motion || !cartesian_velocity) { return false; } cartesian_planner_ = cartesian_motion; - cartesian_velocity_controller_ = std::make_unique( - toCartesianVelocityControllerConfig_( + 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); }; + } + 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; } @@ -1288,25 +1963,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_gen2_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp index 9feebb00..22a78851 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "common/math/transform_math.h" #include "manager/device_manager/include/device_manager.h" @@ -138,6 +140,8 @@ protected: DeviceManager::destroyInstance(); 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( @@ -460,17 +464,20 @@ TEST_F(MotorRobotArmGen2MujocoTest, MoveL) TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) { - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -20.0); + std::unique_ptr viewer; + if (std::getenv("CMVR_MUJOCO_HEADLESS") == nullptr) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -20.0); + } struct CollisionCaseOutcome { std::string name; Result setup_move{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result collision_move{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result recovery{Result::failure(ArmErrorCode::UnknownError, "not run")}; - task::SelfCollisionTaskStatus initial_status; - task::SelfCollisionTaskStatus stop_status; - task::SelfCollisionTaskStatus recovered_status; + safety::SelfCollisionStatus initial_status; + safety::SelfCollisionStatus stop_status; + safety::SelfCollisionStatus recovered_status; CartesianPose start_tcp; CartesianPose final_tcp; std::vector final_position; @@ -553,7 +560,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) name + " start: " + collision_task.detailStatusString()); } outcome.initial_status = collision_task.latestStatus(); - if (outcome.initial_status.level != task::CollisionSafetyLevel::SAFE) { + if (outcome.initial_status.level != safety::CollisionSafetyLevel::SAFE) { throw std::runtime_error( name + " setup pose is not SAFE: " + collision_task.detailStatusString()); @@ -579,9 +586,24 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) }); outcome.collision_move = start_motion(); + const auto simulation_time = [&] { + std::lock_guard lock(world_->mutex()); + return world_->data()->time; + }; + const double wait_start_sim_s = simulation_time(); + const auto wait_start_wall = std::chrono::steady_clock::now(); + // Online control can slow simulation below real time in Debug. + // Bound motion time in simulation, with a wall-clock watchdog. waitFor([&] { - return stop_seen.load() || !monitor_ok.load(); - }, stop_timeout); + return stop_seen.load() || !monitor_ok.load() || + simulation_time() - wait_start_sim_s >= + std::chrono::duration(stop_timeout).count(); + }, stop_timeout * 4); + std::cout << "[MotorRobotArmGen2MujocoTest] collision " << name + << " wait_sim_s=" << simulation_time() - wait_start_sim_s + << ", wait_wall_s=" << std::chrono::duration( + std::chrono::steady_clock::now() - wait_start_wall).count() + << std::endl; if (!stop_seen.load()) { arm_->stopMotion(); monitor_running = false; @@ -689,12 +711,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::seconds(3)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::seconds(3)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); EXPECT_TRUE(worker_error.empty()) << worker_error; @@ -703,16 +729,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) << outcome.name << ": " << outcome.setup_move.message; EXPECT_TRUE(outcome.task_initialized) << outcome.name; EXPECT_TRUE(outcome.task_started) << outcome.name; - EXPECT_EQ(outcome.initial_status.level, task::CollisionSafetyLevel::SAFE) + EXPECT_EQ(outcome.initial_status.level, safety::CollisionSafetyLevel::SAFE) << outcome.name; EXPECT_TRUE(outcome.monitor_ok) << outcome.name; EXPECT_TRUE(outcome.stop_seen) << outcome.name; - EXPECT_EQ(outcome.stop_status.level, task::CollisionSafetyLevel::STOP) + EXPECT_EQ(outcome.stop_status.level, safety::CollisionSafetyLevel::STOP) << outcome.name; EXPECT_TRUE(outcome.stop_status.stop_latched) << outcome.name; EXPECT_NE(outcome.stop_status.event_id, 0U) << outcome.name; EXPECT_EQ(outcome.stop_status.recovery_state, - task::ProtectiveRecoveryState::AVAILABLE) + safety::ProtectiveRecoveryState::AVAILABLE) << outcome.name; EXPECT_GE(outcome.stop_status.recovery_sample_count, 2U) << outcome.name; @@ -725,7 +751,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) << outcome.name << ": " << outcome.recovery.message; EXPECT_FALSE(outcome.recovered_status.stop_latched) << outcome.name; EXPECT_EQ(outcome.recovered_status.recovery_state, - task::ProtectiveRecoveryState::SUCCEEDED) + safety::ProtectiveRecoveryState::SUCCEEDED) << outcome.name; EXPECT_GE(outcome.recovered_status.result.minimum_distance_m, 0.025) << outcome.name; 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..e3f928d4 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: " @@ -239,9 +272,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ) 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 +316,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 +334,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 +353,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 bc5c3efa..b51e7d5a 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,6 +149,12 @@ 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; diff --git a/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h b/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h index 26911c5c..95a522dc 100644 --- a/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h +++ b/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include #include @@ -53,9 +54,16 @@ public: void getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics) override; bool startStreaming() override; void stopStreaming() override; + void getEncodedFrame(StreamFrameData& frame_data, size_t& index) override; + bool waitEncodedFrame(StreamFrameData& frame_data, + size_t& index, + std::chrono::milliseconds timeout) override; bool getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index) override; + bool requestKeyFrame() override; private: + bool startImpl_(); + bool stopImpl_(); bool fetch(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics); void fillIntrinsics(int width, int height, Rs2Intrinsics& intrinsics) const; bool initOffscreen_(); @@ -79,11 +87,19 @@ private: cv::Mat depth; Rs2Intrinsics intrinsics{}; uint64_t frame_id{0}; + uint64_t capture_sequence{0}; + int64_t capture_monotonic_ns{0}; + int64_t capture_utc_ns{0}; bool valid{false}; }; + bool encodeCachedFrame_(const CachedFrame& captured, + StreamFrameData& frame_data, + size_t& next_index); + private: FetchRgbdFn fetch_rgbd_fn_; + std::mutex lifecycle_mtx_; mutable std::mutex mtx_; config::MujocoCameraConfig config_; std::weak_ptr world_; @@ -108,12 +124,19 @@ private: uint64_t last_frame_id_{0}; bool has_last_frame_id_{false}; size_t stream_frame_index_{0}; - bool streaming_{false}; + std::atomic streaming_{false}; + std::mutex stream_mtx_; + size_t streaming_refs_{0}; + uint64_t stream_epoch_{0}; + bool force_key_frame_{false}; + std::atomic encoded_capture_sequence_{0}; + StreamFrameData latest_encoded_frame_; std::shared_ptr rgb_encoder_; mutable std::mutex cache_mtx_; std::condition_variable cache_cv_; CachedFrame latest_frame_; + uint64_t capture_sequence_{0}; std::thread render_thread_; bool render_thread_running_{false}; bool render_stop_requested_{false}; diff --git a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp index a540531f..bd81124b 100644 --- a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp +++ b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp @@ -133,6 +133,12 @@ bool MujocoCamera::init() } bool MujocoCamera::start() +{ + std::lock_guard lock(lifecycle_mtx_); + return startImpl_(); +} + +bool MujocoCamera::startImpl_() { bool initialized = false; { @@ -207,7 +213,7 @@ bool MujocoCamera::start() const bool has_frame = latest_frame_.valid; cache_lock.unlock(); if (!ready || !has_frame) { - stop(); + stopImpl_(); if (ready) { setError_("[MujocoCamera] render thread stopped before producing a frame"); } else { @@ -219,6 +225,12 @@ bool MujocoCamera::start() } bool MujocoCamera::stop() +{ + std::lock_guard lock(lifecycle_mtx_); + return stopImpl_(); +} + +bool MujocoCamera::stopImpl_() { { std::lock_guard lock(cache_mtx_); @@ -237,6 +249,15 @@ bool MujocoCamera::stop() thread_to_join.join(); } + { + std::lock_guard lock(stream_mtx_); + streaming_.store(false); + streaming_refs_ = 0; + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + } { std::lock_guard lock(cache_mtx_); render_thread_running_ = false; @@ -248,13 +269,14 @@ bool MujocoCamera::stop() void MujocoCamera::setFetchRgbdFn(FetchRgbdFn fetch_rgbd_fn) { + std::lock_guard lifecycle_lock(lifecycle_mtx_); bool render_thread_active = false; { std::lock_guard lock(cache_mtx_); render_thread_active = render_thread_running_; } if (render_thread_active) { - stop(); + stopImpl_(); } std::lock_guard lock(mtx_); @@ -307,37 +329,144 @@ void MujocoCamera::getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& bool MujocoCamera::startStreaming() { - if (!start()) { + std::lock_guard lifecycle_lock(lifecycle_mtx_); + if (!startImpl_()) { return false; } - std::lock_guard lock(mtx_); - streaming_ = true; - state_.is_streaming = true; + { + std::lock_guard lock(stream_mtx_); + if (streaming_refs_++ == 0) { + ++stream_epoch_; + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + } + streaming_.store(true); + std::lock_guard state_lock(mtx_); + state_.is_streaming = true; + } + cache_cv_.notify_all(); return true; } void MujocoCamera::stopStreaming() { - std::lock_guard lock(mtx_); - streaming_ = false; - state_.is_streaming = false; - stream_frame_index_ = 0; - rgb_encoder_.reset(); + { + std::lock_guard lock(stream_mtx_); + if (streaming_refs_ == 0 || --streaming_refs_ != 0) { + return; + } + streaming_.store(false); + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + std::lock_guard state_lock(mtx_); + state_.is_streaming = false; + } + cache_cv_.notify_all(); +} + +void MujocoCamera::getEncodedFrame(StreamFrameData& frame_data, size_t& index) +{ + (void)waitEncodedFrame(frame_data, index, std::chrono::milliseconds::zero()); +} + +bool MujocoCamera::waitEncodedFrame(StreamFrameData& frame_data, + size_t& index, + const std::chrono::milliseconds timeout) +{ + const auto deadline = std::chrono::steady_clock::now() + + std::max(timeout, std::chrono::milliseconds::zero()); + uint64_t last_attempted_capture = 0; + + while (true) { + uint64_t encoded_capture = 0; + { + std::lock_guard lock(stream_mtx_); + if (!streaming_.load()) { + return false; + } + if (latest_encoded_frame_.sequence > index) { + frame_data = latest_encoded_frame_; + index = static_cast(frame_data.sequence); + return true; + } + encoded_capture = encoded_capture_sequence_.load(); + } + + CachedFrame captured; + { + std::unique_lock lock(cache_mtx_); + const uint64_t min_capture = std::max(encoded_capture, last_attempted_capture); + const bool ready = cache_cv_.wait_until(lock, deadline, [&] { + return !streaming_.load() || render_stop_requested_ || !render_thread_running_ || + (latest_frame_.valid && latest_frame_.capture_sequence > min_capture); + }); + if (!ready || !streaming_.load() || render_stop_requested_ || + !render_thread_running_ || !latest_frame_.valid) { + return false; + } + captured = latest_frame_; + } + + StreamFrameData encoded; + size_t next_index = index; + if (encodeCachedFrame_(captured, encoded, next_index) && next_index > index) { + frame_data = std::move(encoded); + index = next_index; + return true; + } + last_attempted_capture = std::max(last_attempted_capture, captured.capture_sequence); + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + } } bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index) { - if (!streaming_) { + CachedFrame captured; + { + std::lock_guard lock(cache_mtx_); + if (!latest_frame_.valid || latest_frame_.color.empty()) { + return false; + } + captured = latest_frame_; + } + return encodeCachedFrame_(captured, frame_data, next_index); +} + +bool MujocoCamera::requestKeyFrame() +{ + std::lock_guard lock(stream_mtx_); + if (!streaming_.load()) { return false; } + force_key_frame_ = true; + return true; +} + +bool MujocoCamera::encodeCachedFrame_(const CachedFrame& captured, + StreamFrameData& frame_data, + size_t& next_index) +{ + std::lock_guard lock(stream_mtx_); + if (!streaming_.load() || !captured.valid || captured.color.empty()) { + return false; + } + if (latest_encoded_frame_.sequence != 0 && + captured.capture_sequence <= encoded_capture_sequence_.load()) { + frame_data = latest_encoded_frame_; + next_index = static_cast(frame_data.sequence); + return true; + } - cv::Mat color; - cv::Mat depth; - Rs2Intrinsics intrinsics{}; - if (!fetch(color, depth, intrinsics) || color.empty()) { - return false; - } + const cv::Mat& color = captured.color; + const cv::Mat& depth = captured.depth; + const Rs2Intrinsics& intrinsics = captured.intrinsics; cv::Mat color_to_encode = color; if (encode_width_ > 0 && encode_height_ > 0 && @@ -350,33 +479,59 @@ bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& ne return false; } - frame_data.rgbImage = color.clone(); - frame_data.intrinsics = intrinsics; + StreamFrameData encoded; + // Published capture buffers are immutable. Keep a reference instead of + // copying full-resolution images for every encoded RGB frame. + encoded.rgbImage = color; + encoded.intrinsics = intrinsics; CameraStreamEncodeOptions encode_options; encode_options.draw_timestamp = enable_stream_timestamp_; encode_options.overlay = streamOverlay(); const Rs2Intrinsics encode_intrinsics = scaleIntrinsics( intrinsics, color.cols, color.rows, color_to_encode.cols, color_to_encode.rows); - if (!CameraStreamEncoder::encode(rgb_encoder_, - color_to_encode, - frame_data.rgbFrame, - frame_data.bKey, - encode_intrinsics, - encode_options)) { + rgb_encoder_->frame->pict_type = force_key_frame_ + ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE; + const bool encoded_ok = CameraStreamEncoder::encode(rgb_encoder_, + color_to_encode, + encoded.rgbFrame, + encoded.bKey, + encode_intrinsics, + encode_options); + rgb_encoder_->frame->pict_type = AV_PICTURE_TYPE_NONE; + if (!encoded_ok) { return false; } + if (encoded.bKey) { + force_key_frame_ = false; + } if (!depth.empty()) { - frame_data.depthImage = depth.clone(); + encoded.depthImage = depth; const auto* depth_begin = reinterpret_cast(depth.data); const auto* depth_end = depth_begin + depth.total() * depth.elemSize(); - frame_data.depthFrame.assign(depth_begin, depth_end); + encoded.depthFrame.assign(depth_begin, depth_end); + encoded.depth_width = depth.cols; + encoded.depth_height = depth.rows; } - frame_data.width = color_to_encode.cols; - frame_data.height = color_to_encode.rows; - frame_data.fps = fps; - frame_data.codec = codec_; - frame_data.depthKey = true; - next_index = ++stream_frame_index_; + encoded.width = color_to_encode.cols; + encoded.height = color_to_encode.rows; + encoded.fps = fps; + encoded.codec = codec_; + encoded.depthKey = !depth.empty(); + encoded.stream_epoch = stream_epoch_; + encoded.sequence = ++stream_frame_index_; + encoded.source_frame_number = captured.frame_id; + encoded.capture_monotonic_ns = captured.capture_monotonic_ns; + encoded.capture_utc_ns = captured.capture_utc_ns; + encoded.pts = rgb_encoder_->frame_pts - 1; + encoded.dts = encoded.pts; + encoded.time_base_num = 1; + encoded.time_base_den = fps; + encoded.duration = 1; + + encoded_capture_sequence_.store(captured.capture_sequence); + latest_encoded_frame_ = std::move(encoded); + frame_data = latest_encoded_frame_; + next_index = static_cast(frame_data.sequence); return true; } @@ -598,21 +753,37 @@ void MujocoCamera::renderLoop_() } if (got_frame) { + const auto captured_at = std::chrono::steady_clock::now(); + const auto captured_utc = std::chrono::system_clock::now(); + bool published_frame = false; { std::lock_guard lock(cache_mtx_); - latest_frame_.color = std::move(color); - latest_frame_.depth = std::move(depth); - latest_frame_.intrinsics = intrinsics; - latest_frame_.frame_id = use_external_frames && external_frame_id != 0 - ? external_frame_id - : latest_frame_.frame_id + 1; - latest_frame_.valid = true; + if (!use_external_frames || external_frame_id == 0 || + !latest_frame_.valid || latest_frame_.frame_id != external_frame_id) { + latest_frame_.color = std::move(color); + latest_frame_.depth = std::move(depth); + latest_frame_.intrinsics = intrinsics; + latest_frame_.frame_id = use_external_frames && external_frame_id != 0 + ? external_frame_id + : latest_frame_.frame_id + 1; + latest_frame_.capture_sequence = ++capture_sequence_; + latest_frame_.capture_monotonic_ns = + std::chrono::duration_cast( + captured_at.time_since_epoch()).count(); + latest_frame_.capture_utc_ns = + std::chrono::duration_cast( + captured_utc.time_since_epoch()).count(); + latest_frame_.valid = true; + published_frame = true; + } } { std::lock_guard lock(mtx_); clear_error_(); } - cache_cv_.notify_all(); + if (published_frame) { + cache_cv_.notify_all(); + } } next_tick += period_ticks; @@ -623,7 +794,9 @@ void MujocoCamera::renderLoop_() const auto now = std::chrono::steady_clock::now(); if (next_tick < now) { - next_tick = now + period_ticks; + // The previous capture already ran past its deadline. Retry on + // the next loop rather than adding a second frame period of idle. + next_tick = now; } } diff --git a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp index 67a6c083..1aa6feac 100644 --- a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp +++ b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp @@ -1,10 +1,156 @@ #include +#include +#include +#include +#include + #include "devices/camera/mujoco_camera/include/mujoco_camera.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" namespace { +bool beginsWithAnnexBStartCode(const std::vector& bytes) +{ + return bytes.size() >= 4 && bytes[0] == 0 && bytes[1] == 0 && + (bytes[2] == 1 || (bytes[2] == 0 && bytes[3] == 1)); +} + +bool containsH264IdrNal(const std::vector& bytes) +{ + for (size_t i = 0; i + 4 < bytes.size(); ++i) { + if (bytes[i] != 0 || bytes[i + 1] != 0) { + continue; + } + const size_t start_code_size = bytes[i + 2] == 1 ? 3 : + (bytes[i + 2] == 0 && bytes[i + 3] == 1 ? 4 : 0); + if (start_code_size != 0 && i + start_code_size < bytes.size() && + (bytes[i + start_code_size] & 0x1f) == 5) { + return true; + } + } + return false; +} + +TEST(MujocoCameraTest, WaitEncodedFramePublishesEachExternalFrameOncePerSubscriber) +{ + constexpr int kWidth = 64; + constexpr int kHeight = 48; + std::atomic available_frame_id{1}; + + cmvr::config::MujocoCameraConfig config; + config.set_id("mujoco_external_stream_test_cam"); + auto* render = config.mutable_render(); + render->set_width(kWidth); + render->set_height(kHeight); + render->set_fps(30); + render->set_stream_mode(cmvr::config::STREAM_MODE_RGBD); + auto* encoder = config.mutable_encoder(); + encoder->set_width(kWidth); + encoder->set_height(kHeight); + encoder->set_fps(30); + encoder->set_codec("H264"); + // The deployed external camera permits repeated reads of its last raw + // image. Encoded subscribers must still advance only on a new frame ID. + config.set_consume_new_frame_only(false); + + cmvr::device::MujocoCamera camera(config); + camera.setFetchRgbdFn([&](std::vector& rgb, + std::vector& depth, + int& width, + int& height, + uint64_t& frame_id) { + frame_id = available_frame_id.load(); + if (frame_id == 0) { + return false; + } + width = kWidth; + height = kHeight; + rgb.assign(kWidth * kHeight * 3, static_cast(frame_id * 40)); + depth.assign(kWidth * kHeight, static_cast(frame_id)); + return true; + }); + + cmvr::device::AbstractCamera* base = &camera; + ASSERT_TRUE(camera.init()); + ASSERT_TRUE(base->startStreaming()); + + size_t first_cursor = 0; + cmvr::device::StreamFrameData first; + ASSERT_TRUE(base->waitEncodedFrame(first, first_cursor, std::chrono::seconds(2))); + EXPECT_EQ(first_cursor, 1U); + EXPECT_EQ(first.sequence, 1U); + EXPECT_EQ(first.codec, "H264"); + EXPECT_EQ(first.width, kWidth); + EXPECT_EQ(first.height, kHeight); + EXPECT_TRUE(first.bKey); + EXPECT_TRUE(beginsWithAnnexBStartCode(first.rgbFrame)); + EXPECT_TRUE(containsH264IdrNal(first.rgbFrame)); + + // Each subscriber owns a cursor; reading once must not consume the frame + // for another subscriber, or run the encoder again for the same image. + size_t second_cursor = 0; + cmvr::device::StreamFrameData same_first; + ASSERT_TRUE(base->waitEncodedFrame(same_first, second_cursor, std::chrono::milliseconds(100))); + EXPECT_EQ(second_cursor, first_cursor); + EXPECT_EQ(same_first.sequence, first.sequence); + EXPECT_EQ(same_first.rgbFrame, first.rgbFrame); + + size_t latest_cursor = 0; + cmvr::device::StreamFrameData latest; + ASSERT_TRUE(base->getLatestEncodedFrame(latest, latest_cursor)); + EXPECT_EQ(latest_cursor, first_cursor); + EXPECT_EQ(latest.sequence, first.sequence); + EXPECT_EQ(latest.rgbFrame, first.rgbFrame); + + // Releasing one of two stream leases must not stop the other subscriber. + ASSERT_TRUE(base->startStreaming()); + base->stopStreaming(); + + cmvr::device::StreamFrameData repeated; + EXPECT_FALSE(base->waitEncodedFrame(repeated, first_cursor, std::chrono::milliseconds(150))); + EXPECT_EQ(first_cursor, 1U); + + available_frame_id.store(2); + cmvr::device::StreamFrameData second; + ASSERT_TRUE(base->waitEncodedFrame(second, first_cursor, std::chrono::seconds(2))); + EXPECT_EQ(first_cursor, 2U); + EXPECT_EQ(second.sequence, first.sequence + 1); + EXPECT_FALSE(second.rgbFrame.empty()); + EXPECT_EQ(second.rgbImage.at(0, 0), cv::Vec3b(80, 80, 80)); + + cmvr::device::StreamFrameData same_second; + ASSERT_TRUE(base->waitEncodedFrame(same_second, second_cursor, std::chrono::milliseconds(100))); + EXPECT_EQ(second_cursor, first_cursor); + EXPECT_EQ(same_second.sequence, second.sequence); + EXPECT_EQ(same_second.rgbFrame, second.rgbFrame); + + // The gRPC stream requests an IDR after dropping its pending frames. + // The next captured image must recover decoder continuity immediately. + ASSERT_TRUE(base->requestKeyFrame()); + available_frame_id.store(3); + cmvr::device::StreamFrameData recovered; + ASSERT_TRUE(base->waitEncodedFrame(recovered, first_cursor, std::chrono::seconds(2))); + EXPECT_TRUE(recovered.bKey); + EXPECT_TRUE(containsH264IdrNal(recovered.rgbFrame)); + EXPECT_EQ(recovered.sequence, second.sequence + 1); + + // Keep the caller's cursor across a streaming restart. The new epoch must + // begin with a decodable key frame and a strictly newer sequence. + base->stopStreaming(); + ASSERT_TRUE(base->startStreaming()); + cmvr::device::StreamFrameData restarted; + ASSERT_TRUE(base->waitEncodedFrame(restarted, first_cursor, std::chrono::seconds(2))); + EXPECT_GT(first_cursor, second_cursor); + EXPECT_GT(restarted.sequence, second.sequence); + EXPECT_GT(restarted.stream_epoch, second.stream_epoch); + EXPECT_TRUE(restarted.bKey); + EXPECT_TRUE(beginsWithAnnexBStartCode(restarted.rgbFrame)); + + base->stopStreaming(); + EXPECT_TRUE(camera.stop()); +} + TEST(MujocoCameraTest, CapturesOffscreenRgbdFrame) { cmvr::config::MujocoWorldConfig world_config; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h index f0903a91..c62e3f7c 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h @@ -30,6 +30,11 @@ public: double qd{0.0}; }; + struct CyclicVelocityCommand { + std::uint8_t node_id{0}; + double target_qd{0.0}; + }; + explicit Cia402Protocol(std::shared_ptr bus_runtime, const config::Cia402ProtocolConfig& config); ~Cia402Protocol() override; @@ -55,6 +60,8 @@ public: double target_qd) override; bool commandCyclicPositionsAtomic(const CyclicPositionCommand* commands, std::size_t count); + bool commandCyclicVelocitiesAtomic(const CyclicVelocityCommand* commands, + std::size_t count); bool readFeedbacksAtomic(MotorFeedback* feedbacks, std::size_t count) const; bool commandCyclicVelocity(std::uint8_t node_id, double target_qd) override; @@ -140,8 +147,8 @@ private: std::unique_ptr status_monitor_; config::Cia402ProtocolConfig config_; std::unordered_map nodes_; - std::mutex cyclic_position_mutex_; - std::vector cyclic_position_writes_; + std::mutex cyclic_command_mutex_; + std::vector cyclic_command_writes_; }; } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h index 4bdc2154..04f0b03a 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h @@ -33,6 +33,9 @@ public: const std::vector>& motors, std::vector& positions, std::vector& velocities); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); private: bool hasDependencies_() const; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp index a621ddda..f47a0351 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -20,7 +21,7 @@ Cia402Protocol::Cia402Protocol(std::shared_ptr bus_runt config_(config) { comm_proto = CommProto::ETHERCAT; - cyclic_position_writes_.reserve(512); + cyclic_command_writes_.reserve(512); status_monitor_ = std::make_unique( bus_runtime_, std::chrono::milliseconds(config_.status_poll_period_ms())); } @@ -104,9 +105,9 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( return false; } - std::lock_guard lock(cyclic_position_mutex_); - cyclic_position_writes_.clear(); - cyclic_position_writes_.reserve(count * 2); + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count * 2); for (std::size_t i = 0; i < count; ++i) { const auto& command = commands[i]; @@ -122,13 +123,13 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( } } - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, radToCounts_(command.target_q, *state))); - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, msgs::CIA402_TARGET_VELOCITY_60FF, @@ -136,8 +137,8 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( radPerSecToCounts_(command.target_qd, *state))); } - if (!bus_runtime_->writePdosAtomic(cyclic_position_writes_.data(), - cyclic_position_writes_.size())) { + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), + cyclic_command_writes_.size())) { return false; } @@ -191,16 +192,58 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks, return true; } +bool Cia402Protocol::commandCyclicVelocitiesAtomic( + const CyclicVelocityCommand* commands, + const std::size_t count) +{ + if (!bus_runtime_ || !commands || count == 0 || count > 256) { + return false; + } + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const auto& command = commands[i]; + const auto* state = findNodeState_(command.node_id); + if (!std::isfinite(command.target_qd) || !state || + !hasValidConversion_(command.node_id, *state) || + state->mode != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY || + !status_monitor_->isNodeOperational(command.node_id)) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (commands[previous].node_id == command.node_id) { + return false; + } + } + const double counts = command.target_qd / (2.0 * M_PI) * + state->gear_ratio * state->encoder_counts_per_rev; + if (!std::isfinite(counts) || + counts < std::numeric_limits::min() || + counts > std::numeric_limits::max()) { + return false; + } + cyclic_command_writes_.push_back( + EthercatMotorBusRuntime::makePdoWrite( + command.node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, + radPerSecToCounts_(command.target_qd, *state))); + } + // The bus validates every PDO before changing the shared output frame. + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), count)) { + return false; + } + for (std::size_t i = 0; i < count; ++i) { + auto& state = nodeState_(commands[i].node_id); + state.target_velocity = radPerSecToCounts_(commands[i].target_qd, state); + } + return true; +} + bool Cia402Protocol::commandCyclicVelocity(const std::uint8_t node_id, const double target_qd) { - auto& state = nodeState_(node_id); - if (!hasValidConversion_(node_id, state) || - !status_monitor_->isNodeOperational(node_id)) { - return false; - } - state.target_velocity = radPerSecToCounts_(target_qd, state); - return writeTargetsForMode_(node_id, state.mode, state); + const CyclicVelocityCommand command{node_id, target_qd}; + return commandCyclicVelocitiesAtomic(&command, 1); } bool Cia402Protocol::commandCyclicTorque(const std::uint8_t node_id, diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp index 20fcbfa2..0eb39ca7 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp @@ -151,6 +151,42 @@ bool EyouMotor::commandCyclicPositionsAtomic( return protocol && protocol->commandCyclicPositionsAtomic(commands.data(), motors.size()); } +bool EyouMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size() || motors.size() > 256) { + return false; + } + std::array lock_order{}; + std::array commands{}; + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !std::isfinite(velocities[i]) || !motor->hasDependencies_() || + !motor->hasValidConversion_()) { + return false; + } + if (protocol && protocol != motor->cia402_protocol_) { + return false; + } + protocol = motor->cia402_protocol_; + for (std::size_t previous = 0; previous < i; ++previous) { + if (lock_order[previous] == motor.get()) { + return false; + } + } + lock_order[i] = motor.get(); + commands[i] = {motor->node_id_, velocities[i]}; + } + std::sort(lock_order.begin(), lock_order.begin() + motors.size(), std::less{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(lock_order[i]->mtx_); + } + return protocol->commandCyclicVelocitiesAtomic(commands.data(), motors.size()); +} + bool EyouMotor::readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, diff --git a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h index 57c97387..c4f75b48 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h +++ b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h @@ -49,6 +49,13 @@ public: const std::vector>& motors, const std::vector& positions, const std::vector& velocities); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); + static bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities); private: bool holdPosition_(); diff --git a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp index 447e8d18..588fd20c 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp +++ b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -276,6 +277,83 @@ bool MujocoMotor::commandCyclicPositionsAtomic( return true; } +bool MujocoMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + std::vector selected; + selected.reserve(motors.size()); + std::shared_ptr world; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !std::isfinite(velocities[i])) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world) || + std::find(selected.begin(), selected.end(), motor.get()) != selected.end()) { + return false; + } + world = motor_world; + selected.push_back(motor.get()); + } + + auto lock_order = selected; + std::sort(lock_order.begin(), lock_order.end(), std::less{}); + std::vector> locks; + locks.reserve(lock_order.size()); + for (auto* motor : lock_order) { + locks.emplace_back(motor->mtx_); + } + std::vector names; + std::vector clamped_velocities; + names.reserve(selected.size()); + clamped_velocities.reserve(selected.size()); + for (std::size_t i = 0; i < selected.size(); ++i) { + if (!selected[i]->initialized_) { + return false; + } + names.push_back(selected[i]->info_.joint_name); + clamped_velocities.push_back(selected[i]->clampQd_(velocities[i])); + } + if (!world->setJointTargetVelocities(names, clamped_velocities)) { + return false; + } + for (auto* motor : selected) { + motor->mode_ = msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY; + } + return true; +} + +bool MujocoMotor::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities) +{ + if (motors.empty()) { + return false; + } + std::shared_ptr world; + std::vector names; + names.reserve(motors.size()); + for (const auto& item : motors) { + const auto motor = std::dynamic_pointer_cast(item); + if (!motor) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world)) { + return false; + } + world = motor_world; + names.push_back(motor->info_.joint_name); + } + return world->getJointStates(names, positions, velocities); +} + double MujocoMotor::clampQ_(const double q) const { if (std::isfinite(info_.limit_q_lb) && std::isfinite(info_.limit_q_ub) && diff --git a/cmvr-es/devices/motor/manager/CMakeLists.txt b/cmvr-es/devices/motor/manager/CMakeLists.txt index 8ea5f495..6b9b0613 100644 --- a/cmvr-es/devices/motor/manager/CMakeLists.txt +++ b/cmvr-es/devices/motor/manager/CMakeLists.txt @@ -13,7 +13,7 @@ target_link_libraries(motor_manager cmvr_es::device::ti5_canopen_motor_driver cmvr_es::device::mujoco_motor_driver cmvr_es::device::ethercat_motor_driver - cmvr_es::ik_solver + cmvr_es::environment glog ) diff --git a/cmvr-es/devices/motor/manager/include/motor_manager.h b/cmvr-es/devices/motor/manager/include/motor_manager.h index 45e8ab3e..6a59030a 100644 --- a/cmvr-es/devices/motor/manager/include/motor_manager.h +++ b/cmvr-es/devices/motor/manager/include/motor_manager.h @@ -50,6 +50,9 @@ public: const std::vector>& motors, const std::vector& positions, const std::vector& velocities) const; + bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const; bool readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 1d1b262e..86e93e69 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -8,7 +8,6 @@ #include #include -#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include "common/base/logging/logger.h" #include "common/config/config_files.h" #include "devices/motor/bus_runtime/abstract_motor_bus_runtime.h" @@ -22,6 +21,7 @@ #include "devices/motor/drivers/mujoco/include/mujoco_motor.h" #include "devices/motor/drivers/ti5_canopen/include/ti5_motor.h" #include "devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h" +#include "environment/include/robot_model.h" namespace cmvr::device { @@ -311,18 +311,107 @@ bool MotorManager::commandCyclicPositionsAtomic( return false; } +bool MotorManager::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i] || !std::isfinite(velocities[i])) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } + if (std::dynamic_pointer_cast(motors.front())) { + return EyouMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) + << "[MotorManager] TI5 uses non-atomic cyclic velocity commands"; + }); + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicVelocity(velocities[i])) { + // CAN commands cannot be rolled back; attempt to stop every motor. + for (const auto& motor : motors) { + if (!motor->commandCyclicVelocity(0.0)) { + CMVR_LOG(ERROR) << "[MotorManager] failed to zero TI5 motor: " + << motor->id(); + } + } + return false; + } + } + return true; + } + CMVR_LOG(ERROR) << "[MotorManager] atomic cyclic velocity is unsupported for motor type: " + << motors.front()->typeName(); + return false; +} + bool MotorManager::readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, std::vector& velocities) const { - if (motors.empty()) { + if (motors.empty() || &positions == &velocities) { return false; } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } if (std::dynamic_pointer_cast(motors.front())) { return EyouMotor::readFeedbacksAtomic(motors, positions, velocities); } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::readFeedbacksAtomic(motors, positions, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) << "[MotorManager] TI5 feedback is read per motor, not atomically"; + }); + std::vector q(motors.size()); + std::vector qd(motors.size()); + for (std::size_t i = 0; i < motors.size(); ++i) { + q[i] = motors[i]->getQ(); + qd[i] = motors[i]->getQd(); + if (!std::isfinite(q[i]) || !std::isfinite(qd[i])) { + return false; + } + } + positions = std::move(q); + velocities = std::move(qd); + return true; + } CMVR_LOG(ERROR) << "[MotorManager] atomic feedback is unsupported for motor type: " << motors.front()->typeName(); @@ -387,22 +476,18 @@ bool MotorManager::applyConfiguredJointLimits_(const config::MotorGroupConfig& g return false; } - UrdfParser parser; - std::string error; - if (!parser.loadModel(urdf_path, &error)) { - CMVR_LOG(ERROR) << "[MotorManager] Failed to load joint limit URDF: " << error; + RobotModel model; + if (!model.loadUrdf(urdf_path)) { + CMVR_LOG(ERROR) << "[MotorManager] Failed to load joint limit URDF: " << urdf_path; return false; } - const auto& model = parser.model(); - for (pinocchio::JointIndex joint_id = 1; joint_id < model.njoints; ++joint_id) { - if (model.nqs[joint_id] != 1 || model.nvs[joint_id] != 1) { - continue; - } + for (std::size_t index = 0; index < model.joint_names.size(); ++index) { + const auto& joint_limit = model.joint_limits[index]; config::JointLimitConfig limit; - limit.set_joint_name(model.names[joint_id]); - limit.set_q_lb(model.lowerPositionLimit[model.idx_qs[joint_id]]); - limit.set_q_ub(model.upperPositionLimit[model.idx_qs[joint_id]]); - limit.set_qd(model.velocityLimit[model.idx_vs[joint_id]]); + limit.set_joint_name(model.joint_names[index]); + limit.set_q_lb(joint_limit.lower); + limit.set_q_ub(joint_limit.upper); + limit.set_qd(joint_limit.max_velocity); limits_by_joint[limit.joint_name()] = limit; } } else { 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..4d488303 --- /dev/null +++ b/cmvr-es/environment/include/robot_model.h @@ -0,0 +1,104 @@ +#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; + 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/safety/CMakeLists.txt b/cmvr-es/safety/CMakeLists.txt new file mode 100644 index 00000000..8940faf0 --- /dev/null +++ b/cmvr-es/safety/CMakeLists.txt @@ -0,0 +1,18 @@ +add_library(self_collision_monitor SHARED + self_collision/src/self_collision_monitor.cpp +) + +target_include_directories(self_collision_monitor PUBLIC + ${PROJECT_SOURCE_DIR}/cmvr-es +) + +target_link_libraries(self_collision_monitor + PUBLIC + cmvr_es::collision_checker + cmvr_es::proto + PRIVATE + cmvr_es::logging +) + +add_library(cmvr_es::self_collision_monitor ALIAS self_collision_monitor) +install(TARGETS self_collision_monitor LIBRARY DESTINATION lib) diff --git a/cmvr-es/safety/self_collision/include/self_collision_monitor.h b/cmvr-es/safety/self_collision/include/self_collision_monitor.h new file mode 100644 index 00000000..815d315c --- /dev/null +++ b/cmvr-es/safety/self_collision/include/self_collision_monitor.h @@ -0,0 +1,92 @@ +#ifndef CMVR_ES_SELF_COLLISION_MONITOR_H +#define CMVR_ES_SELF_COLLISION_MONITOR_H + +#include +#include +#include +#include +#include +#include + +#include "algorithms/collision_detection/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "cmvr/config/collision_config.pb.h" +#include "devices/arm/robot_arm.h" + +namespace cmvr::safety { + +enum class CollisionSafetyLevel { + UNKNOWN = 0, + SAFE, + WARNING, + STOP, +}; + +enum class ProtectiveRecoveryState { + IDLE = 0, + AVAILABLE, + RECOVERING, + SUCCEEDED, + FAILED, +}; + +struct SelfCollisionStatus { + CollisionSafetyLevel level{CollisionSafetyLevel::UNKNOWN}; + CollisionResult result; + bool stop_latched{false}; + std::uint64_t event_id{0}; + ProtectiveRecoveryState recovery_state{ProtectiveRecoveryState::IDLE}; + std::size_t recovery_sample_count{0}; + std::string recovery_error; +}; + +// The arm must outlive the monitor. The caller initializes it before use and +// serializes step() calls. No worker thread is created here; step() must continue +// during protective stops and while requestRecovery() runs on another thread. +class SelfCollisionMonitor { +public: + enum class State { UNINITIALIZED = 0, IDLE, RUNNING, STOPPED, FAILED }; + + SelfCollisionMonitor(const config::SelfCollisionMonitorConfig& config, + device::RobotArm& arm); + + bool init(); + bool start(); + bool step(); + void stop(); + + State state() const; + std::string detailStatusString() const; + SelfCollisionStatus latestStatus() const; + device::Result requestRecovery(std::uint64_t event_id); + +private: + static bool validateConfig(const config::SelfCollisionMonitorConfig& config, + std::string* error); + static const char* safetyLevelToString(CollisionSafetyLevel level); + static const char* recoveryStateToString(ProtectiveRecoveryState state); + void recordJointSample_(const device::JointGroupState& joint_state, + DistanceSamplingPolicy::Clock::time_point now); + + config::SelfCollisionMonitorConfig config_; + device::RobotArm& arm_; + CollisionChecker checker_; + DistanceSamplingPolicy sampling_; + + mutable std::mutex mutex_; + std::condition_variable recovery_cv_; + State state_{State::UNINITIALIZED}; + SelfCollisionStatus latest_status_{}; + std::deque joint_history_; + device::JointTrajectory recovery_path_; + DistanceSamplingPolicy::Clock::time_point history_epoch_{}; + std::optional recovery_clear_since_; + double recovery_best_distance_m_{0.0}; + bool recovery_clear_confirmed_{false}; + std::uint64_t next_event_id_{1}; + std::string last_error_; +}; + +} // namespace cmvr::safety + +#endif // CMVR_ES_SELF_COLLISION_MONITOR_H diff --git a/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp b/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp new file mode 100644 index 00000000..8dddecf4 --- /dev/null +++ b/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp @@ -0,0 +1,557 @@ +#include "safety/self_collision/include/self_collision_monitor.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr::safety { +namespace { + +const char* monitorStateToString(const SelfCollisionMonitor::State state) +{ + using State = SelfCollisionMonitor::State; + switch (state) { + case State::UNINITIALIZED: return "UNINITIALIZED"; + case State::IDLE: return "IDLE"; + case State::RUNNING: return "RUNNING"; + case State::STOPPED: return "STOPPED"; + case State::FAILED: return "FAILED"; + } + return "UNKNOWN"; +} + +} // namespace + +SelfCollisionMonitor::SelfCollisionMonitor( + const config::SelfCollisionMonitorConfig& config, device::RobotArm& arm) + : config_(config), arm_(arm) +{ +} + +bool SelfCollisionMonitor::validateConfig(const config::SelfCollisionMonitorConfig& config, + std::string* error) +{ + auto fail = [error](const std::string& message) { + if (error) { + *error = message; + } + return false; + }; + + const auto& sampling = config.sampling(); + if (!std::isfinite(sampling.max_geometry_displacement_m()) || + sampling.max_geometry_displacement_m() <= 0.0) { + return fail("max_geometry_displacement_m must be finite and positive"); + } + if (!std::isfinite(sampling.max_check_period_s()) || + sampling.max_check_period_s() <= 0.0) { + return fail("max_check_period_s must be finite and positive"); + } + + const auto& safety = config.safety(); + if (!std::isfinite(safety.stop_distance_m()) || safety.stop_distance_m() < 0.0) { + return fail("stop_distance_m must be finite and non-negative"); + } + if (!std::isfinite(safety.warning_distance_m()) || + safety.warning_distance_m() < safety.stop_distance_m()) { + return fail("warning_distance_m must be finite and not less than stop_distance_m"); + } + const auto& recovery = config.recovery(); + if (!std::isfinite(recovery.clear_distance_m()) || + recovery.clear_distance_m() <= safety.warning_distance_m()) { + return fail("recovery clear_distance_m must be finite and greater than warning_distance_m"); + } + if (!std::isfinite(recovery.stable_period_s()) || + recovery.stable_period_s() <= 0.0) { + return fail("recovery stable_period_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_joint_velocity_rad_s()) || + recovery.max_joint_velocity_rad_s() <= 0.0) { + return fail("recovery max_joint_velocity_rad_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_joint_acceleration_rad_s2()) || + recovery.max_joint_acceleration_rad_s2() <= 0.0) { + return fail("recovery max_joint_acceleration_rad_s2 must be finite and positive"); + } + if (!std::isfinite(recovery.history_duration_s()) || + recovery.history_duration_s() <= 0.0) { + return fail("recovery history_duration_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_distance_regression_m()) || + recovery.max_distance_regression_m() < 0.0) { + return fail("recovery max_distance_regression_m must be finite and non-negative"); + } + if (error) { + error->clear(); + } + return true; +} + +bool SelfCollisionMonitor::init() +{ + std::string error; + if (!validateConfig(config_, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + auto* arm = &arm_; + const auto model = arm->getRobotModel(); + if (!model.valid()) { + std::lock_guard lock(mutex_); + last_error_ = "Robot arm model is invalid"; + state_ = State::FAILED; + return false; + } + + if (!checker_.init(config_.checker(), model, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + const DistanceSamplingOptions sampling_options{ + config_.sampling().max_geometry_displacement_m(), + config_.sampling().max_check_period_s(), + }; + if (!sampling_.configure(sampling_options, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + { + std::lock_guard lock(mutex_); + latest_status_ = {}; + joint_history_.clear(); + recovery_path_.clear(); + history_epoch_ = DistanceSamplingPolicy::Clock::now(); + recovery_clear_since_.reset(); + recovery_best_distance_m_ = 0.0; + recovery_clear_confirmed_ = false; + next_event_id_ = 1; + last_error_.clear(); + state_ = State::IDLE; + } + CMVR_LOG(INFO) << "[SelfCollisionMonitor] Initialized dof=" << checker_.dof() + << ", active_pairs=" << checker_.activePairCount(); + return true; +} + +bool SelfCollisionMonitor::start() +{ + std::lock_guard lock(mutex_); + if (state_ == State::RUNNING) { + return true; + } + if (state_ != State::IDLE && state_ != State::STOPPED) { + last_error_ = "Self-collision monitor is not initialized"; + state_ = State::FAILED; + return false; + } + sampling_.reset(); + latest_status_ = {}; + joint_history_.clear(); + recovery_path_.clear(); + history_epoch_ = DistanceSamplingPolicy::Clock::now(); + recovery_clear_since_.reset(); + recovery_best_distance_m_ = 0.0; + recovery_clear_confirmed_ = false; + last_error_.clear(); + state_ = State::RUNNING; + return true; +} + +bool SelfCollisionMonitor::step() +{ + auto* arm = &arm_; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return false; + } + } + + const auto fail_monitoring = [&](std::string error) { + bool cancel_recovery = false; + { + std::lock_guard lock(mutex_); + cancel_recovery = + latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; + if (cancel_recovery) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = error; + } + last_error_ = std::move(error); + state_ = State::FAILED; + recovery_cv_.notify_all(); + } + if (cancel_recovery) { + (void)arm->protectiveStop(); + } + return false; + }; + + const auto joint_state = arm->getJointState(); + const auto model = arm->getRobotModel(); + if (!joint_state.validForModel(model)) { + return fail_monitoring("Robot arm returned an invalid joint state"); + } + + const auto now = DistanceSamplingPolicy::Clock::now(); + recordJointSample_(joint_state, now); + + std::vector bodies; + try { + bodies = checker_.collisionBodies(joint_state.position); + } catch (const std::exception& error) { + return fail_monitoring(error.what()); + } + + if (!sampling_.shouldCheck(bodies, now)) { + return true; + } + + CollisionResult result = checker_.check(bodies); + if (!result.valid) { + return fail_monitoring( + result.error.empty() ? "Self-collision distance check failed" : result.error); + } + sampling_.markChecked(bodies, now); + + CollisionSafetyLevel level = CollisionSafetyLevel::SAFE; + if (result.minimum_distance_m <= config_.safety().stop_distance_m()) { + level = CollisionSafetyLevel::STOP; + } else if (result.minimum_distance_m <= config_.safety().warning_distance_m()) { + level = CollisionSafetyLevel::WARNING; + } + + bool trigger_stop = false; + bool abort_recovery = false; + CollisionSafetyLevel previous_level = CollisionSafetyLevel::UNKNOWN; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return true; + } + previous_level = latest_status_.level; + latest_status_.level = level; + latest_status_.result = result; + + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + if (arm->isEmergencyStopped()) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Protective recovery interrupted by emergency stop"; + recovery_clear_since_.reset(); + abort_recovery = true; + recovery_cv_.notify_all(); + } else if (result.minimum_distance_m + + config_.recovery().max_distance_regression_m() < + recovery_best_distance_m_) { + std::ostringstream stream; + stream << "Protective recovery distance regressed from " + << recovery_best_distance_m_ << " m to " + << result.minimum_distance_m << " m"; + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = stream.str(); + recovery_clear_since_.reset(); + abort_recovery = true; + recovery_cv_.notify_all(); + } else { + recovery_best_distance_m_ = std::max( + recovery_best_distance_m_, result.minimum_distance_m); + if (result.minimum_distance_m >= + config_.recovery().clear_distance_m()) { + if (!recovery_clear_since_) { + recovery_clear_since_ = now; + } else if (std::chrono::duration( + now - *recovery_clear_since_).count() >= + config_.recovery().stable_period_s()) { + recovery_clear_confirmed_ = true; + recovery_cv_.notify_all(); + } + } else { + recovery_clear_since_.reset(); + recovery_clear_confirmed_ = false; + } + } + } else if (level == CollisionSafetyLevel::STOP && + !latest_status_.stop_latched) { + latest_status_.stop_latched = true; + latest_status_.event_id = next_event_id_++; + latest_status_.recovery_state = ProtectiveRecoveryState::AVAILABLE; + latest_status_.recovery_error.clear(); + recovery_path_.assign(joint_history_.begin(), joint_history_.end()); + latest_status_.recovery_sample_count = recovery_path_.size(); + trigger_stop = true; + } else if (!latest_status_.stop_latched && + result.minimum_distance_m >= + config_.recovery().clear_distance_m()) { + joint_history_.clear(); + device::JointTrajectoryPoint sample; + sample.time_s = std::chrono::duration(now - history_epoch_).count(); + sample.position = joint_state.position; + sample.velocity = joint_state.velocity; + joint_history_.push_back(std::move(sample)); + } + } + + if (level != previous_level) { + if (level == CollisionSafetyLevel::SAFE) { + CMVR_LOG(INFO) << "[SelfCollisionMonitor] level=" << safetyLevelToString(level) + << ", distance_m=" << result.minimum_distance_m + << ", pair=" << result.first << "/" << result.second; + } else { + CMVR_LOG(WARNING) << "[SelfCollisionMonitor] level=" << safetyLevelToString(level) + << ", distance_m=" << result.minimum_distance_m + << ", pair=" << result.first << "/" << result.second; + } + } + + if (abort_recovery) { + (void)arm->protectiveStop(); + } else if (trigger_stop) { + const auto stop_result = arm->protectiveStop(); + if (!stop_result.ok()) { + std::lock_guard lock(mutex_); + last_error_ = "Protective stop failed: " + stop_result.message; + state_ = State::FAILED; + return false; + } + } + return true; +} + +void SelfCollisionMonitor::recordJointSample_( + const device::JointGroupState& joint_state, + const DistanceSamplingPolicy::Clock::time_point now) +{ + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING || latest_status_.stop_latched) { + return; + } + + device::JointTrajectoryPoint sample; + sample.time_s = std::chrono::duration(now - history_epoch_).count(); + sample.position = joint_state.position; + sample.velocity = joint_state.velocity; + if (!joint_history_.empty() && sample.time_s <= joint_history_.back().time_s) { + return; + } + joint_history_.push_back(std::move(sample)); + + const double oldest_time_s = joint_history_.back().time_s - + config_.recovery().history_duration_s(); + while (joint_history_.size() > 1 && + joint_history_.front().time_s < oldest_time_s) { + joint_history_.pop_front(); + } +} + +device::Result SelfCollisionMonitor::requestRecovery(const std::uint64_t event_id) +{ + auto* arm = &arm_; + device::JointTrajectory path; + device::MotionOptions options; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return device::Result::failure( + device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: collision monitor is not running"); + } + if (!latest_status_.stop_latched || + latest_status_.recovery_state != ProtectiveRecoveryState::AVAILABLE) { + return device::Result::failure( + device::ArmErrorCode::CommandRejected, + "Protective recovery rejected: no recoverable collision stop is available"); + } + if (event_id == 0 || event_id != latest_status_.event_id) { + return device::Result::failure( + device::ArmErrorCode::InvalidArgument, + "Protective recovery rejected: event_id does not match the active stop"); + } + if (!arm_.isProtectiveStopped() || arm_.isEmergencyStopped()) { + return device::Result::failure( + arm_.isEmergencyStopped() + ? device::ArmErrorCode::RobotInEmergencyStop + : device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: arm safety state is invalid"); + } + if (recovery_path_.size() < 2) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Protective recovery path contains fewer than two samples"; + return device::Result::failure( + device::ArmErrorCode::CommandRejected, + latest_status_.recovery_error); + } + + path = recovery_path_; + options.velocity = config_.recovery().max_joint_velocity_rad_s(); + options.acceleration = + config_.recovery().max_joint_acceleration_rad_s2(); + latest_status_.recovery_state = ProtectiveRecoveryState::RECOVERING; + latest_status_.recovery_error.clear(); + recovery_best_distance_m_ = latest_status_.result.minimum_distance_m; + recovery_clear_since_.reset(); + recovery_clear_confirmed_ = false; + } + + CMVR_LOG(INFO) << "[SelfCollisionMonitor] recovery requested event_id=" + << event_id << ", samples=" << path.size() + << ", max_joint_velocity_rad_s=" + << options.velocity + << ", max_joint_acceleration_rad_s2=" + << options.acceleration; + const auto playback_result = arm->recoverProtectiveStop(path, options); + if (!playback_result.ok()) { + std::lock_guard lock(mutex_); + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = playback_result.message; + } + const std::string recovery_error = latest_status_.recovery_error; + recovery_cv_.notify_all(); + return device::Result::failure(playback_result.code, recovery_error); + } + + { + std::unique_lock lock(mutex_); + const auto clear_timeout = std::chrono::duration( + config_.recovery().stable_period_s() + 2.0); + const bool completed = recovery_cv_.wait_for(lock, clear_timeout, [&] { + return state_ != State::RUNNING || recovery_clear_confirmed_ || + latest_status_.recovery_state != ProtectiveRecoveryState::RECOVERING; + }); + if (!completed || !recovery_clear_confirmed_) { + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = completed + ? "Protective recovery ended before the clear distance was confirmed" + : "Protective recovery clear-distance confirmation timed out"; + } + const std::string error = latest_status_.recovery_error; + lock.unlock(); + (void)arm->protectiveStop(); + return device::Result::failure( + device::ArmErrorCode::CommandFailed, error); + } + + latest_status_.stop_latched = false; + latest_status_.recovery_state = ProtectiveRecoveryState::SUCCEEDED; + latest_status_.recovery_error.clear(); + joint_history_.clear(); + joint_history_.push_back(path.front()); + recovery_path_.clear(); + latest_status_.recovery_sample_count = 0; + } + + const auto unlock_result = arm->unlockProtectiveStop(); + if (!unlock_result.ok()) { + std::lock_guard lock(mutex_); + latest_status_.stop_latched = true; + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Failed to unlock protective stop: " + unlock_result.message; + return device::Result::failure( + unlock_result.code, latest_status_.recovery_error); + } + + CMVR_LOG(INFO) << "[SelfCollisionMonitor] recovery completed event_id=" + << event_id << ", clear_distance_m=" + << config_.recovery().clear_distance_m(); + return device::Result::success(); +} + +void SelfCollisionMonitor::stop() +{ + auto* arm = &arm_; + bool cancel_recovery = false; + { + std::lock_guard lock(mutex_); + cancel_recovery = + latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; + if (state_ != State::FAILED) { + state_ = State::STOPPED; + } + recovery_cv_.notify_all(); + } + if (cancel_recovery) { + (void)arm->protectiveStop(); + } +} + +SelfCollisionMonitor::State SelfCollisionMonitor::state() const +{ + std::lock_guard lock(mutex_); + return state_; +} + +std::string SelfCollisionMonitor::detailStatusString() const +{ + std::lock_guard lock(mutex_); + if (!last_error_.empty()) { + return std::string(monitorStateToString(state_)) + " " + last_error_; + } + std::ostringstream stream; + stream << monitorStateToString(state_) + << " level=" << safetyLevelToString(latest_status_.level) + << " stop_latched=" << latest_status_.stop_latched + << " event_id=" << latest_status_.event_id + << " recovery=" + << recoveryStateToString(latest_status_.recovery_state); + if (latest_status_.result.valid) { + stream << " distance_m=" << std::setprecision(6) + << latest_status_.result.minimum_distance_m + << " pair=" << latest_status_.result.first + << "/" << latest_status_.result.second; + } + if (!latest_status_.recovery_error.empty()) { + stream << " recovery_error=" << latest_status_.recovery_error; + } + return stream.str(); +} + +SelfCollisionStatus SelfCollisionMonitor::latestStatus() const +{ + std::lock_guard lock(mutex_); + return latest_status_; +} + +const char* SelfCollisionMonitor::safetyLevelToString(const CollisionSafetyLevel level) +{ + switch (level) { + case CollisionSafetyLevel::UNKNOWN: return "UNKNOWN"; + case CollisionSafetyLevel::SAFE: return "SAFE"; + case CollisionSafetyLevel::WARNING: return "WARNING"; + case CollisionSafetyLevel::STOP: return "STOP"; + } + return "UNKNOWN"; +} + +const char* SelfCollisionMonitor::recoveryStateToString( + const ProtectiveRecoveryState state) +{ + switch (state) { + case ProtectiveRecoveryState::IDLE: return "IDLE"; + case ProtectiveRecoveryState::AVAILABLE: return "AVAILABLE"; + case ProtectiveRecoveryState::RECOVERING: return "RECOVERING"; + case ProtectiveRecoveryState::SUCCEEDED: return "SUCCEEDED"; + case ProtectiveRecoveryState::FAILED: return "FAILED"; + } + return "UNKNOWN"; +} + +} // namespace cmvr::safety diff --git a/cmvr-es/service/grpc/action/tests/action_queue_test.cpp b/cmvr-es/service/grpc/action/tests/action_queue_test.cpp index 54a8da3f..edc2f15e 100644 --- a/cmvr-es/service/grpc/action/tests/action_queue_test.cpp +++ b/cmvr-es/service/grpc/action/tests/action_queue_test.cpp @@ -29,7 +29,7 @@ public: std::string typeName() const override { return "FakeActionQueueArm"; } bool stop() override { return stopMotion().ok(); } - device::RobotModel getRobotModel() const override { return model_; } + RobotModel getRobotModel() const override { return model_; } std::size_t getDof() const override { return model_.dof; } device::ArmState getRobotState() const override { return {}; } device::JointGroupState getJointState() const override { return {}; } @@ -204,7 +204,7 @@ private: : device::Result::success(); } - device::RobotModel model_; + RobotModel model_; mutable std::mutex mutex_; std::condition_variable cv_; std::vector calls_; 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 1ebd4bf9..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,6 +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& 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); @@ -66,6 +76,8 @@ public: const std::vector& positions, const std::vector& velocities); bool setJointTargetVelocity(const std::string& joint_name, double velocity); + bool setJointTargetVelocities(const std::vector& joint_names, + const std::vector& velocities); mjModel* model(); mjData* data(); @@ -110,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 0f29ad02..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,6 +323,35 @@ bool MujocoWorld::setJointPosition(const std::string& joint_name, const double p return true; } +bool MujocoWorld::getJointStates(const std::vector& joint_names, + std::vector& positions, + std::vector& velocities) const +{ + if (joint_names.empty() || &positions == &velocities) { + return false; + } + std::lock_guard lock(mutex_); + std::vector joints; + 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; + } + joints.push_back(joint); + } + positions.resize(joints.size()); + velocities.resize(joints.size()); + for (std::size_t i = 0; i < joints.size(); ++i) { + positions[i] = data_->qpos[joints[i]->qpos_adr]; + velocities[i] = data_->qvel[joints[i]->qvel_adr]; + } + return true; +} + bool MujocoWorld::setJointVelocity(const std::string& joint_name, const double velocity) { std::lock_guard lock(mutex_); @@ -410,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_; @@ -621,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; @@ -640,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/cmvr-es/task/CMakeLists.txt b/cmvr-es/task/CMakeLists.txt index b10b0978..8cdabc3c 100644 --- a/cmvr-es/task/CMakeLists.txt +++ b/cmvr-es/task/CMakeLists.txt @@ -11,7 +11,7 @@ target_link_libraries(task cmvr_es::common cmvr_es::ik_solver cmvr_es::base_motion - cmvr_es::self_collision_checker + cmvr_es::self_collision_monitor PRIVATE cmvr_es::device_manager ) @@ -25,6 +25,8 @@ add_executable(touch_screen_task_test target_link_libraries(touch_screen_task_test PRIVATE cmvr_es::task + cmvr_es::joint_path_planner + cmvr_es::collision_checker cmvr_es::device::arm cmvr_es::device::motor_manager cmvr_es::device::mujoco_motor_driver diff --git a/cmvr-es/task/self_collision_task/include/self_collision_task.h b/cmvr-es/task/self_collision_task/include/self_collision_task.h index 938207e8..527b39f5 100644 --- a/cmvr-es/task/self_collision_task/include/self_collision_task.h +++ b/cmvr-es/task/self_collision_task/include/self_collision_task.h @@ -1,53 +1,20 @@ #ifndef CMVR_ES_SELF_COLLISION_TASK_H #define CMVR_ES_SELF_COLLISION_TASK_H -#include -#include -#include #include -#include -#include #include -#include -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" #include "cmvr/config/self_collision_task_config/self_collision_task_config.pb.h" -#include "devices/arm/robot_arm.h" +#include "safety/self_collision/include/self_collision_monitor.h" #include "task/task.h" namespace cmvr::task { -enum class CollisionSafetyLevel { - UNKNOWN = 0, - SAFE, - WARNING, - STOP, -}; - -enum class ProtectiveRecoveryState { - IDLE = 0, - AVAILABLE, - RECOVERING, - SUCCEEDED, - FAILED, -}; - -struct SelfCollisionTaskStatus { - CollisionSafetyLevel level{CollisionSafetyLevel::UNKNOWN}; - SelfCollisionResult result; - bool stop_latched{false}; - std::uint64_t event_id{0}; - ProtectiveRecoveryState recovery_state{ProtectiveRecoveryState::IDLE}; - std::size_t recovery_sample_count{0}; - std::string recovery_error; -}; - class SelfCollisionTask final : public Task { public: explicit SelfCollisionTask(const config::SelfCollisionTaskConfig& config); - const std::string& id() const override { return id_; } + const std::string& id() const override { return config_.id(); } TaskRunMode runMode() const override { return TaskRunMode::PERIODIC_STEP; } bool init() override; @@ -56,41 +23,22 @@ public: void stop() override; TaskState state() const override; - bool isBusy() const override; - bool isFinished() const override; - bool isFailed() const override; - std::string stateString() const override; + bool isBusy() const override { return state() == TaskState::RUNNING; } + bool isFinished() const override { return state() == TaskState::STOPPED; } + bool isFailed() const override { return state() == TaskState::FAILED; } + std::string stateString() const override { return taskStateToString(state()); } std::string detailStatusString() const override; - SelfCollisionTaskStatus latestStatus() const; + safety::SelfCollisionStatus latestStatus() const; device::Result requestRecovery(std::uint64_t event_id); private: - static bool validateConfig(const config::SelfCollisionTaskConfig& config, - std::string* error); - static const char* safetyLevelToString(CollisionSafetyLevel level); - static const char* recoveryStateToString(ProtectiveRecoveryState state); - void recordJointSample_(const device::JointGroupState& joint_state, - DistanceSamplingPolicy::Clock::time_point now); - config::SelfCollisionTaskConfig config_; - std::string id_; + // Bound by init() before scheduling; the arm outlives the monitor. std::shared_ptr arm_; - SelfCollisionChecker checker_; - DistanceSamplingPolicy sampling_; - - mutable std::mutex mutex_; - std::condition_variable recovery_cv_; - TaskState state_{TaskState::UNINITIALIZED}; - SelfCollisionTaskStatus latest_status_{}; - std::deque joint_history_; - device::JointTrajectory recovery_path_; - DistanceSamplingPolicy::Clock::time_point history_epoch_{}; - std::optional recovery_clear_since_; - double recovery_best_distance_m_{0.0}; - bool recovery_clear_confirmed_{false}; - std::uint64_t next_event_id_{1}; - std::string last_error_; + std::unique_ptr monitor_; + TaskState init_state_{TaskState::UNINITIALIZED}; + std::string init_error_; }; } // namespace cmvr::task diff --git a/cmvr-es/task/self_collision_task/src/self_collision_task.cpp b/cmvr-es/task/self_collision_task/src/self_collision_task.cpp index 00464c60..9c7b064a 100644 --- a/cmvr-es/task/self_collision_task/src/self_collision_task.cpp +++ b/cmvr-es/task/self_collision_task/src/self_collision_task.cpp @@ -1,597 +1,106 @@ #include "task/self_collision_task/include/self_collision_task.h" -#include -#include -#include -#include -#include -#include - -#include "common/base/logging/logger.h" #include "manager/device_manager/include/device_manager.h" namespace cmvr::task { SelfCollisionTask::SelfCollisionTask(const config::SelfCollisionTaskConfig& config) - : config_(config), - id_(config.id()) + : config_(config) { } -bool SelfCollisionTask::validateConfig(const config::SelfCollisionTaskConfig& config, - std::string* error) -{ - auto fail = [error](const std::string& message) { - if (error) { - *error = message; - } - return false; - }; - - if (config.id().empty()) { - return fail("Self-collision task id is empty"); - } - if (config.arm_id().empty()) { - return fail("Self-collision task arm_id is empty"); - } - if (config.checker().urdf_path().empty()) { - return fail("Self-collision checker URDF path is empty"); - } - const auto& sampling = config.sampling(); - if (!std::isfinite(sampling.max_geometry_displacement_m()) || - sampling.max_geometry_displacement_m() <= 0.0) { - return fail("max_geometry_displacement_m must be finite and positive"); - } - if (!std::isfinite(sampling.max_check_period_s()) || - sampling.max_check_period_s() <= 0.0) { - return fail("max_check_period_s must be finite and positive"); - } - - const auto& safety = config.safety(); - if (!std::isfinite(safety.stop_distance_m()) || safety.stop_distance_m() < 0.0) { - return fail("stop_distance_m must be finite and non-negative"); - } - if (!std::isfinite(safety.warning_distance_m()) || - safety.warning_distance_m() < safety.stop_distance_m()) { - return fail("warning_distance_m must be finite and not less than stop_distance_m"); - } - const auto& recovery = config.recovery(); - if (!std::isfinite(recovery.clear_distance_m()) || - recovery.clear_distance_m() <= safety.warning_distance_m()) { - return fail("recovery clear_distance_m must be finite and greater than warning_distance_m"); - } - if (!std::isfinite(recovery.stable_period_s()) || - recovery.stable_period_s() <= 0.0) { - return fail("recovery stable_period_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_joint_velocity_rad_s()) || - recovery.max_joint_velocity_rad_s() <= 0.0) { - return fail("recovery max_joint_velocity_rad_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_joint_acceleration_rad_s2()) || - recovery.max_joint_acceleration_rad_s2() <= 0.0) { - return fail("recovery max_joint_acceleration_rad_s2 must be finite and positive"); - } - if (!std::isfinite(recovery.history_duration_s()) || - recovery.history_duration_s() <= 0.0) { - return fail("recovery history_duration_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_distance_regression_m()) || - recovery.max_distance_regression_m() < 0.0) { - return fail("recovery max_distance_regression_m must be finite and non-negative"); - } - for (const auto& pair : config.checker().ignored_pairs()) { - if (pair.first().empty() || pair.second().empty() || pair.first() == pair.second()) { - return fail("ignored_pairs entries require two different non-empty links"); - } - } - if (error) { - error->clear(); - } - return true; -} - bool SelfCollisionTask::init() { - std::string error; - if (!validateConfig(config_, &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; + monitor_.reset(); + arm_.reset(); + init_error_.clear(); + init_state_ = TaskState::FAILED; + if (config_.id().empty()) { + init_error_ = "Self-collision task id is empty"; + return false; + } + if (config_.arm_id().empty()) { + init_error_ = "Self-collision task arm_id is empty"; return false; } - auto arm = device::DeviceManager::getInstance().getDevice( + arm_ = device::DeviceManager::getInstance().getDevice( config_.arm_id()); - if (!arm) { - std::lock_guard lock(mutex_); - last_error_ = "Robot arm not found: " + config_.arm_id(); - state_ = TaskState::FAILED; + if (!arm_) { + init_error_ = "Robot arm not found: " + config_.arm_id(); return false; } - const auto model = arm->getRobotModel(); - if (!model.valid()) { - std::lock_guard lock(mutex_); - last_error_ = "Robot arm model is invalid: " + config_.arm_id(); - state_ = TaskState::FAILED; - return false; - } - - SelfCollisionOptions checker_options; - checker_options.ignored_pairs.reserve(config_.checker().ignored_pairs_size()); - for (const auto& pair : config_.checker().ignored_pairs()) { - checker_options.ignored_pairs.push_back({pair.first(), pair.second()}); - } - if (!checker_.init(config_.checker().urdf_path(), - model.joint_names, - checker_options, - &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; - return false; - } - - const DistanceSamplingOptions sampling_options{ - config_.sampling().max_geometry_displacement_m(), - config_.sampling().max_check_period_s(), - }; - if (!sampling_.configure(sampling_options, &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; - return false; - } - - { - std::lock_guard lock(mutex_); - arm_ = std::move(arm); - latest_status_ = {}; - joint_history_.clear(); - recovery_path_.clear(); - history_epoch_ = DistanceSamplingPolicy::Clock::now(); - recovery_clear_since_.reset(); - recovery_best_distance_m_ = 0.0; - recovery_clear_confirmed_ = false; - next_event_id_ = 1; - last_error_.clear(); - state_ = TaskState::IDLE; - } - CMVR_LOG(INFO) << "[SelfCollisionTask] Initialized id=" << id_ - << ", arm=" << config_.arm_id() - << ", dof=" << checker_.dof() - << ", active_pairs=" << checker_.activePairCount(); - return true; + config::SelfCollisionMonitorConfig monitor_config; + *monitor_config.mutable_checker() = config_.checker(); + *monitor_config.mutable_sampling() = config_.sampling(); + *monitor_config.mutable_safety() = config_.safety(); + *monitor_config.mutable_recovery() = config_.recovery(); + monitor_ = std::make_unique(monitor_config, *arm_); + return monitor_->init(); } bool SelfCollisionTask::start() { - std::lock_guard lock(mutex_); - if (state_ == TaskState::RUNNING) { - return true; - } - if (state_ != TaskState::IDLE && state_ != TaskState::STOPPED) { - last_error_ = "Self-collision task is not initialized"; - state_ = TaskState::FAILED; + if (!monitor_) { + init_error_ = "Self-collision task is not initialized"; + init_state_ = TaskState::FAILED; return false; } - sampling_.reset(); - latest_status_ = {}; - joint_history_.clear(); - recovery_path_.clear(); - history_epoch_ = DistanceSamplingPolicy::Clock::now(); - recovery_clear_since_.reset(); - recovery_best_distance_m_ = 0.0; - recovery_clear_confirmed_ = false; - last_error_.clear(); - state_ = TaskState::RUNNING; - return true; + return monitor_->start(); } -bool SelfCollisionTask::step(const double dt) +bool SelfCollisionTask::step(double /*dt*/) { - (void)dt; - std::shared_ptr arm; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return false; - } - arm = arm_; - } - - const auto fail_monitoring = [&](std::string error) { - bool cancel_recovery = false; - { - std::lock_guard lock(mutex_); - cancel_recovery = - latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; - if (cancel_recovery) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = error; - } - last_error_ = std::move(error); - state_ = TaskState::FAILED; - recovery_cv_.notify_all(); - } - if (cancel_recovery) { - (void)arm->protectiveStop(); - } - return false; - }; - - const auto joint_state = arm->getJointState(); - const auto model = arm->getRobotModel(); - if (!joint_state.validForModel(model)) { - return fail_monitoring("Robot arm returned an invalid joint state"); - } - - const auto now = DistanceSamplingPolicy::Clock::now(); - recordJointSample_(joint_state, now); - - CollisionGeometrySnapshot snapshot; - std::string error; - if (!checker_.makeSnapshot(joint_state.position, &snapshot, &error)) { - return fail_monitoring(std::move(error)); - } - - if (!sampling_.shouldCheck(snapshot, now)) { - return true; - } - - SelfCollisionResult result = checker_.check(snapshot); - if (!result.valid) { - return fail_monitoring( - result.error.empty() ? "Self-collision distance check failed" : result.error); - } - sampling_.markChecked(snapshot, now); - - CollisionSafetyLevel level = CollisionSafetyLevel::SAFE; - if (result.minimum_distance_m <= config_.safety().stop_distance_m()) { - level = CollisionSafetyLevel::STOP; - } else if (result.minimum_distance_m <= config_.safety().warning_distance_m()) { - level = CollisionSafetyLevel::WARNING; - } - - bool trigger_stop = false; - bool abort_recovery = false; - CollisionSafetyLevel previous_level = CollisionSafetyLevel::UNKNOWN; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return true; - } - previous_level = latest_status_.level; - latest_status_.level = level; - latest_status_.result = result; - - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - if (arm->isEmergencyStopped()) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Protective recovery interrupted by emergency stop"; - recovery_clear_since_.reset(); - abort_recovery = true; - recovery_cv_.notify_all(); - } else if (result.minimum_distance_m + - config_.recovery().max_distance_regression_m() < - recovery_best_distance_m_) { - std::ostringstream stream; - stream << "Protective recovery distance regressed from " - << recovery_best_distance_m_ << " m to " - << result.minimum_distance_m << " m"; - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = stream.str(); - recovery_clear_since_.reset(); - abort_recovery = true; - recovery_cv_.notify_all(); - } else { - recovery_best_distance_m_ = std::max( - recovery_best_distance_m_, result.minimum_distance_m); - if (result.minimum_distance_m >= - config_.recovery().clear_distance_m()) { - if (!recovery_clear_since_) { - recovery_clear_since_ = now; - } else if (std::chrono::duration( - now - *recovery_clear_since_).count() >= - config_.recovery().stable_period_s()) { - recovery_clear_confirmed_ = true; - recovery_cv_.notify_all(); - } - } else { - recovery_clear_since_.reset(); - recovery_clear_confirmed_ = false; - } - } - } else if (level == CollisionSafetyLevel::STOP && - !latest_status_.stop_latched) { - latest_status_.stop_latched = true; - latest_status_.event_id = next_event_id_++; - latest_status_.recovery_state = ProtectiveRecoveryState::AVAILABLE; - latest_status_.recovery_error.clear(); - recovery_path_.assign(joint_history_.begin(), joint_history_.end()); - latest_status_.recovery_sample_count = recovery_path_.size(); - trigger_stop = true; - } else if (!latest_status_.stop_latched && - result.minimum_distance_m >= - config_.recovery().clear_distance_m()) { - joint_history_.clear(); - device::JointTrajectoryPoint sample; - sample.time_s = std::chrono::duration(now - history_epoch_).count(); - sample.position = joint_state.position; - sample.velocity = joint_state.velocity; - joint_history_.push_back(std::move(sample)); - } - } - - if (level != previous_level) { - if (level == CollisionSafetyLevel::SAFE) { - CMVR_LOG(INFO) << "[SelfCollisionTask] level=" << safetyLevelToString(level) - << ", distance_m=" << result.minimum_distance_m - << ", pair=" << result.first << "/" << result.second; - } else { - CMVR_LOG(WARNING) << "[SelfCollisionTask] level=" << safetyLevelToString(level) - << ", distance_m=" << result.minimum_distance_m - << ", pair=" << result.first << "/" << result.second; - } - } - - if (abort_recovery) { - (void)arm->protectiveStop(); - } else if (trigger_stop) { - const auto stop_result = arm->protectiveStop(); - if (!stop_result.ok()) { - std::lock_guard lock(mutex_); - last_error_ = "Protective stop failed: " + stop_result.message; - state_ = TaskState::FAILED; - return false; - } - } - return true; -} - -void SelfCollisionTask::recordJointSample_( - const device::JointGroupState& joint_state, - const DistanceSamplingPolicy::Clock::time_point now) -{ - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING || latest_status_.stop_latched) { - return; - } - - device::JointTrajectoryPoint sample; - sample.time_s = std::chrono::duration(now - history_epoch_).count(); - sample.position = joint_state.position; - sample.velocity = joint_state.velocity; - if (!joint_history_.empty() && sample.time_s <= joint_history_.back().time_s) { - return; - } - joint_history_.push_back(std::move(sample)); - - const double oldest_time_s = joint_history_.back().time_s - - config_.recovery().history_duration_s(); - while (joint_history_.size() > 1 && - joint_history_.front().time_s < oldest_time_s) { - joint_history_.pop_front(); - } -} - -device::Result SelfCollisionTask::requestRecovery(const std::uint64_t event_id) -{ - std::shared_ptr arm; - device::JointTrajectory path; - device::MotionOptions options; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return device::Result::failure( - device::ArmErrorCode::RobotNotReady, - "Protective recovery rejected: collision task is not running"); - } - if (!latest_status_.stop_latched || - latest_status_.recovery_state != ProtectiveRecoveryState::AVAILABLE) { - return device::Result::failure( - device::ArmErrorCode::CommandRejected, - "Protective recovery rejected: no recoverable collision stop is available"); - } - if (event_id == 0 || event_id != latest_status_.event_id) { - return device::Result::failure( - device::ArmErrorCode::InvalidArgument, - "Protective recovery rejected: event_id does not match the active stop"); - } - if (!arm_ || !arm_->isProtectiveStopped() || arm_->isEmergencyStopped()) { - return device::Result::failure( - arm_ && arm_->isEmergencyStopped() - ? device::ArmErrorCode::RobotInEmergencyStop - : device::ArmErrorCode::RobotNotReady, - "Protective recovery rejected: arm safety state is invalid"); - } - if (recovery_path_.size() < 2) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Protective recovery path contains fewer than two samples"; - return device::Result::failure( - device::ArmErrorCode::CommandRejected, - latest_status_.recovery_error); - } - - arm = arm_; - path = recovery_path_; - options.velocity = config_.recovery().max_joint_velocity_rad_s(); - options.acceleration = - config_.recovery().max_joint_acceleration_rad_s2(); - latest_status_.recovery_state = ProtectiveRecoveryState::RECOVERING; - latest_status_.recovery_error.clear(); - recovery_best_distance_m_ = latest_status_.result.minimum_distance_m; - recovery_clear_since_.reset(); - recovery_clear_confirmed_ = false; - } - - CMVR_LOG(INFO) << "[SelfCollisionTask] recovery requested event_id=" - << event_id << ", samples=" << path.size() - << ", max_joint_velocity_rad_s=" - << options.velocity - << ", max_joint_acceleration_rad_s2=" - << options.acceleration; - const auto playback_result = arm->recoverProtectiveStop(path, options); - if (!playback_result.ok()) { - std::lock_guard lock(mutex_); - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = playback_result.message; - } - const std::string recovery_error = latest_status_.recovery_error; - recovery_cv_.notify_all(); - return device::Result::failure(playback_result.code, recovery_error); - } - - { - std::unique_lock lock(mutex_); - const auto clear_timeout = std::chrono::duration( - config_.recovery().stable_period_s() + 2.0); - const bool completed = recovery_cv_.wait_for(lock, clear_timeout, [&] { - return state_ != TaskState::RUNNING || recovery_clear_confirmed_ || - latest_status_.recovery_state != ProtectiveRecoveryState::RECOVERING; - }); - if (!completed || !recovery_clear_confirmed_) { - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = completed - ? "Protective recovery ended before the clear distance was confirmed" - : "Protective recovery clear-distance confirmation timed out"; - } - const std::string error = latest_status_.recovery_error; - lock.unlock(); - (void)arm->protectiveStop(); - return device::Result::failure( - device::ArmErrorCode::CommandFailed, error); - } - - latest_status_.stop_latched = false; - latest_status_.recovery_state = ProtectiveRecoveryState::SUCCEEDED; - latest_status_.recovery_error.clear(); - joint_history_.clear(); - joint_history_.push_back(path.front()); - recovery_path_.clear(); - latest_status_.recovery_sample_count = 0; - } - - const auto unlock_result = arm->unlockProtectiveStop(); - if (!unlock_result.ok()) { - std::lock_guard lock(mutex_); - latest_status_.stop_latched = true; - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Failed to unlock protective stop: " + unlock_result.message; - return device::Result::failure( - unlock_result.code, latest_status_.recovery_error); - } - - CMVR_LOG(INFO) << "[SelfCollisionTask] recovery completed event_id=" - << event_id << ", clear_distance_m=" - << config_.recovery().clear_distance_m(); - return device::Result::success(); + return monitor_ && monitor_->step(); } void SelfCollisionTask::stop() { - std::shared_ptr arm; - bool cancel_recovery = false; - { - std::lock_guard lock(mutex_); - cancel_recovery = - latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; - arm = arm_; - if (state_ != TaskState::FAILED) { - state_ = TaskState::STOPPED; - } - recovery_cv_.notify_all(); - } - if (cancel_recovery && arm) { - (void)arm->protectiveStop(); + if (monitor_) { + monitor_->stop(); + } else if (init_state_ != TaskState::FAILED) { + init_state_ = TaskState::STOPPED; } } TaskState SelfCollisionTask::state() const { - std::lock_guard lock(mutex_); - return state_; -} - -bool SelfCollisionTask::isBusy() const -{ - return state() == TaskState::RUNNING; -} - -bool SelfCollisionTask::isFinished() const -{ - return state() == TaskState::STOPPED; -} - -bool SelfCollisionTask::isFailed() const -{ - return state() == TaskState::FAILED; -} - -std::string SelfCollisionTask::stateString() const -{ - return taskStateToString(state()); + if (!monitor_) { + return init_state_; + } + using State = safety::SelfCollisionMonitor::State; + switch (monitor_->state()) { + case State::UNINITIALIZED: return TaskState::UNINITIALIZED; + case State::IDLE: return TaskState::IDLE; + case State::RUNNING: return TaskState::RUNNING; + case State::STOPPED: return TaskState::STOPPED; + case State::FAILED: return TaskState::FAILED; + } + return TaskState::FAILED; } std::string SelfCollisionTask::detailStatusString() const { - std::lock_guard lock(mutex_); - if (!last_error_.empty()) { - return std::string(taskStateToString(state_)) + " " + last_error_; + if (monitor_) { + return monitor_->detailStatusString(); } - std::ostringstream stream; - stream << taskStateToString(state_) - << " level=" << safetyLevelToString(latest_status_.level) - << " stop_latched=" << latest_status_.stop_latched - << " event_id=" << latest_status_.event_id - << " recovery=" - << recoveryStateToString(latest_status_.recovery_state); - if (latest_status_.result.valid) { - stream << " distance_m=" << std::setprecision(6) - << latest_status_.result.minimum_distance_m - << " pair=" << latest_status_.result.first - << "/" << latest_status_.result.second; - } - if (!latest_status_.recovery_error.empty()) { - stream << " recovery_error=" << latest_status_.recovery_error; - } - return stream.str(); + return init_error_.empty() ? stateString() : stateString() + " " + init_error_; } -SelfCollisionTaskStatus SelfCollisionTask::latestStatus() const +safety::SelfCollisionStatus SelfCollisionTask::latestStatus() const { - std::lock_guard lock(mutex_); - return latest_status_; + return monitor_ ? monitor_->latestStatus() : safety::SelfCollisionStatus{}; } -const char* SelfCollisionTask::safetyLevelToString(const CollisionSafetyLevel level) +device::Result SelfCollisionTask::requestRecovery(const std::uint64_t event_id) { - switch (level) { - case CollisionSafetyLevel::UNKNOWN: return "UNKNOWN"; - case CollisionSafetyLevel::SAFE: return "SAFE"; - case CollisionSafetyLevel::WARNING: return "WARNING"; - case CollisionSafetyLevel::STOP: return "STOP"; + if (!monitor_) { + return device::Result::failure( + device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: collision task is not initialized"); } - return "UNKNOWN"; -} - -const char* SelfCollisionTask::recoveryStateToString( - const ProtectiveRecoveryState state) -{ - switch (state) { - case ProtectiveRecoveryState::IDLE: return "IDLE"; - case ProtectiveRecoveryState::AVAILABLE: return "AVAILABLE"; - case ProtectiveRecoveryState::RECOVERING: return "RECOVERING"; - case ProtectiveRecoveryState::SUCCEEDED: return "SUCCEEDED"; - case ProtectiveRecoveryState::FAILED: return "FAILED"; - } - return "UNKNOWN"; + return monitor_->requestRecovery(event_id); } } // namespace cmvr::task diff --git a/cmvr-es/task/touch_screen_task/include/touch_screen_task.h b/cmvr-es/task/touch_screen_task/include/touch_screen_task.h index 4e8decfc..4a9009c1 100644 --- a/cmvr-es/task/touch_screen_task/include/touch_screen_task.h +++ b/cmvr-es/task/touch_screen_task/include/touch_screen_task.h @@ -4,8 +4,10 @@ #define CMVR_ES_TOUCH_SCREEN_TASK_H #include +#include #include #include +#include #include #include #include @@ -36,7 +38,9 @@ public: DWELLING, // 已检测到接触,保持当前位置短暂停留。 RETRACTING, // 回退阶段:沿设定回退方向离开屏幕。 DONE, // 整个流程成功完成。 - FAILED // 流程失败并已停止。 + FAILED, // 流程失败并已停止。 + PREPARING, // 视觉定位预接近目标。 + APPROACHING // MoveP 预接近,完成后进入视觉对齐。 }; enum class Status { @@ -59,7 +63,11 @@ public: STOPPED, // 被外部 stop() 主动停止。 ROBOT_STATE_FAILED, // 读取机器人状态失败。 ROBOT_COMMAND_FAILED, // 向机器人下发控制命令失败。 - TASK_BUSY // 已有触屏流程正在运行,新的 touch 请求被拒绝。 + TASK_BUSY, // 已有触屏流程正在运行,新的 touch 请求被拒绝。 + PREPARING, + APPROACHING, + APPROACH_FAILED, + APPROACH_TIMEOUT }; explicit TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg); @@ -116,8 +124,22 @@ private: bool isBusyUnlocked() const; bool startFromPixelUnlocked(int u, int v); void stopUnlocked(); + void resetRunState(); bool applyConfig(); + bool stepPreparing(); + bool stepApproaching(); + void cancelApproach(); bool stepAligning(double dt); + // Perception helpers return readiness; waiting keeps stepAligning active. + bool updateAlignmentAnchor(Eigen::Vector3d& p_target_G); + bool updateAlignmentTcpPose(); + bool updatePbvsTarget(const Eigen::Vector3d& p_target_G, + const Eigen::Matrix4d& T_G_P); + bool mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P, + const PbvsController::Output& output, + device::CartesianVelocity& twist_B); + bool applyAlignmentCommand(const PbvsController::Output& output, + const device::CartesianVelocity& twist_B); bool stepTouching(); bool stepDwelling(); bool stepRetracting(); @@ -125,8 +147,7 @@ private: void stopPbvsMotion(); bool buildInitJointPositions(std::vector& positions_out) const; bool isAtInitPosition(const std::vector& positions) const; - bool moveToInitPositionBeforeStartIfEnabled(); - bool moveToInitPositionIfEnabled() const; + bool moveToInitPositionIfEnabled(bool enabled, bool use_move_j = false); bool readCurrentTouchPointPositionBase(Eigen::Vector3d& p_out) const; void logTouchingSpeedLState() const; @@ -147,6 +168,9 @@ private: private: mutable std::mutex mutex_; + // The motion worker captures values only; it never takes the task mutex. + std::future approach_motion_; + std::shared_ptr> approach_cancel_; // The display worker never takes mutex_ or uses the PBVS perception state. std::mutex coordinate_overlay_mutex_; std::condition_variable coordinate_overlay_cv_; @@ -164,8 +188,11 @@ private: perception::TagRelativeTarget3D tracker_; perception::TagRelativeTcpPose tcp_pose_tracker_; PbvsController pbvs_; - cmvr::config::TouchScreenTaskConfig config_{}; - bool config_valid_{false}; + const cmvr::config::TouchScreenTaskConfig config_; + const bool config_valid_; + device::AbstractDexHand::TactileRegionKey tactile_region_{ + device::AbstractDexHand::FingerType::INDEX, + device::AbstractDexHand::TactileRegion::TIP}; Phase phase_{Phase::IDLE}; Phase phase_after_retract_{Phase::DONE}; @@ -190,7 +217,7 @@ private: Eigen::Vector3d last_align_error_screen_tag_{Eigen::Vector3d::Zero()}; Eigen::Matrix4d T_H_P_{Eigen::Matrix4d::Identity()}; double pbvs_command_acceleration_{0.25}; - // Initialization MoveJ is skipped only when both position and velocity + // Initialization MoveP is skipped only when both position and velocity // are within these configured limits. double init_skip_position_tolerance_rad_{1e-3}; double init_skip_velocity_tolerance_rad_s_{1e-2}; diff --git a/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp b/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp index 98374c3b..1605bd8d 100644 --- a/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp +++ b/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -21,19 +22,6 @@ namespace cmvr::task { namespace { -// The initialization move is a safety repositioning step. Avoid replanning -// an already settled arm, while still requiring a stopped joint velocity so a -// moving arm is never mistaken for being at the initial pose. -device::CartesianVelocity toCartesianVelocity(const Eigen::Matrix& twist) { - return {twist[0], twist[1], twist[2], twist[3], twist[4], twist[5]}; -} - -Eigen::Matrix toEigen6(const device::CartesianVelocity& twist) { - Eigen::Matrix out; - out << twist.vx, twist.vy, twist.vz, twist.wx, twist.wy, twist.wz; - return out; -} - bool computeLinearMoveDeltaTool(const Eigen::Matrix& twist_base, const double move_length, Eigen::Vector3d& delta_out) { @@ -167,30 +155,20 @@ bool extractProjectedYawAboutTargetNormal(const Eigen::Matrix3d& R_target, return std::isfinite(yaw_rad_out); } -bool appendRequestedTactileRegions( +bool isTactileRegionSupported( const device::AbstractDexHand::FingerType finger, - const device::AbstractDexHand::TactileRegion region, - std::vector& regions_out) { - using DeviceTactileRegion = device::AbstractDexHand::TactileRegion; - + const device::AbstractDexHand::TactileRegion region) { + using Region = device::AbstractDexHand::TactileRegion; switch (region) { - case device::AbstractDexHand::TactileRegion::TIP: - regions_out.emplace_back(finger, DeviceTactileRegion::TIP); - return true; - case device::AbstractDexHand::TactileRegion::FINGER: - regions_out.emplace_back(finger, DeviceTactileRegion::FINGER); - return true; - case device::AbstractDexHand::TactileRegion::PAD: - regions_out.emplace_back(finger, DeviceTactileRegion::PAD); - return true; - case device::AbstractDexHand::TactileRegion::THUMB_MIDDLE: - if (finger != device::AbstractDexHand::FingerType::THUMB) { - return false; - } - regions_out.emplace_back(finger, DeviceTactileRegion::THUMB_MIDDLE); + case Region::TIP: + case Region::FINGER: + case Region::PAD: return true; + case Region::THUMB_MIDDLE: + return finger == device::AbstractDexHand::FingerType::THUMB; + default: + return false; } - return false; } perception::AprilTagPerception::DepthPolicy toDepthPolicy( @@ -233,29 +211,6 @@ device::AbstractDexHand::FingerType toFingerType(const cmvr::config::TouchScreen return device::AbstractDexHand::FingerType::INDEX; } -const char* fingerTypeToString(const device::AbstractDexHand::FingerType finger) { - switch (finger) { - case device::AbstractDexHand::FingerType::PINKY: return "PINKY"; - case device::AbstractDexHand::FingerType::RING: return "RING"; - case device::AbstractDexHand::FingerType::MIDDLE: return "MIDDLE"; - case device::AbstractDexHand::FingerType::INDEX: return "INDEX"; - case device::AbstractDexHand::FingerType::THUMB: return "THUMB"; - case device::AbstractDexHand::FingerType::PALM: return "PALM"; - } - return "UNKNOWN"; -} - -const char* tactileRegionToString(const device::AbstractDexHand::TactileRegion region) { - switch (region) { - case device::AbstractDexHand::TactileRegion::TIP: return "TIP"; - case device::AbstractDexHand::TactileRegion::FINGER: return "FINGER"; - case device::AbstractDexHand::TactileRegion::PAD: return "PAD"; - case device::AbstractDexHand::TactileRegion::THUMB_MIDDLE: return "THUMB_MIDDLE"; - case device::AbstractDexHand::TactileRegion::PALM_PAD: return "PALM_PAD"; - } - return "UNKNOWN"; -} - device::AbstractDexHand::TactileRegion toTactileRegion( const cmvr::config::TouchScreenTactileRegion region) { switch (region) { @@ -276,52 +231,42 @@ device::AbstractDexHand::TactileRegion toTactileRegion( TouchScreenTask::TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg) : id_(cfg.id()), tracker_(nullptr), - config_(cfg) { - config_valid_ = validateConfig(config_); + config_(cfg), + config_valid_(validateConfig(config_)) { if (!config_valid_) { last_status_ = Status::INVALID_CONFIG; } } TouchScreenTask::~TouchScreenTask() { + cancelApproach(); stopCoordinateOverlayWorker(); } bool TouchScreenTask::init() { - if (!config_valid_) { - last_status_ = Status::INVALID_CONFIG; - return false; + { + std::lock_guard lock(mutex_); + stopUnlocked(); + stopCoordinateOverlayWorker(); + initialized_ = false; + last_status_ = config_valid_ ? Status::NOT_INITIALIZED : Status::INVALID_CONFIG; + if (!config_valid_) return false; } const auto& devices = config_.devices(); - const auto& perception_config = config_.perception(); - if (!devices.has_arm_id() || devices.arm_id().empty() || - !devices.has_dexhand_id() || devices.dexhand_id().empty() || - !devices.has_camera_id() || devices.camera_id().empty() || - !devices.has_external_camera_id() || devices.external_camera_id().empty() || - !perception_config.has_hand_camera() || - !perception_config.hand_camera().has_depth_policy() || - !perception_config.hand_camera().has_target_point_method()) { - last_status_ = Status::INVALID_CONFIG; - return false; - } - auto& dm = device::DeviceManager::getInstance(); auto arm = dm.getDevice(devices.arm_id()); auto dexhand = dm.getDevice(devices.dexhand_id()); - const auto& hand_camera_config = perception_config.hand_camera(); auto camera = dm.getDevice(devices.camera_id()); auto external_camera = dm.getDevice(devices.external_camera_id()); if (!camera || !camera->start()) { CMVR_LOG(ERROR) << "[TouchScreenTask] Failed to start camera: " << devices.camera_id(); - last_status_ = Status::NOT_INITIALIZED; return false; } if (!external_camera || !external_camera->start()) { CMVR_LOG(ERROR) << "[TouchScreenTask] Failed to start external camera: " << devices.external_camera_id(); - last_status_ = Status::NOT_INITIALIZED; return false; } return init(arm, dexhand, camera, external_camera); @@ -343,6 +288,8 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, const std::shared_ptr& camera, const std::shared_ptr& external_camera) { std::lock_guard lock(mutex_); + stopUnlocked(); + initialized_ = false; stopCoordinateOverlayWorker(); arm_ = arm; dexhand_ = dexhand; @@ -355,33 +302,10 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, return false; } - if ((config_.initialization().before_start() || config_.initialization().after_finish()) && - config_.initialization().joint_positions().empty()) { - initialized_ = false; - last_status_ = Status::INVALID_CONFIG; - return false; - } - - const auto& perception_config = config_.perception(); - const auto& tags = perception_config.tags(); - const auto& hand_camera_config = perception_config.hand_camera(); perception_ = std::make_shared(camera_); - perception_->setTagSize(tags.screen().size_m()); external_perception_ = std::make_shared(external_camera_); - external_perception_->setTagSize(tags.screen().size_m()); - tracker_.setPerception(perception_); - tracker_.setTargetPointMethod(toTargetPointMethod( - hand_camera_config.target_point_method())); - - tcp_pose_tracker_.setPerception(external_perception_); - tcp_pose_tracker_.setScreenTagId(tags.screen().id()); - tcp_pose_tracker_.setHandTagId(tags.hand().id()); - - // Publish the presentation settings immediately so a gRPC stream started - // before the first periodic task tick uses the configured behavior. - publishCoordinateOverlay(); initialized_ = applyConfig(); if (initialized_) { @@ -390,28 +314,10 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, tcp_pose_tracker_.clear(); pbvs_.reset(); phase_ = Phase::IDLE; - phase_after_retract_ = Phase::DONE; - final_status_after_retract_ = Status::DONE; - target_locked_ = false; - pbvs_target_initialized_ = false; - touch_command_started_ = false; - retract_command_started_ = false; - align_stable_count_ = 0; - last_active_tag_id_ = -1; - last_touch_pressure_sum_ = 0.0; - last_touch_resultant_fz_ = 0.0; - last_touch_nonzero_count_ = 0; - last_align_error_screen_tag_.setZero(); - touch_start_position_valid_ = false; - touch_start_position_base_.setZero(); - retract_start_position_valid_ = false; - retract_start_position_base_.setZero(); - have_last_T_B_G_ = false; - last_T_B_G_.setIdentity(); - max_T_B_G_translation_delta_m_ = 0.0; - max_T_B_G_rotation_delta_rad_ = 0.0; - last_touch_pressure_log_time_ = Clock::time_point{}; + resetRunState(); last_status_ = Status::IDLE; + // Make presentation settings available before the first task tick. + publishCoordinateOverlay(); startCoordinateOverlayWorker(); } else { last_status_ = Status::INVALID_CONFIG; @@ -443,8 +349,33 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) { return false; } + // A failed run keeps its original status until a new run passes preflight. + // In particular, do not move to the initial/approach pose with a latched speedL fault. + const auto reject_start = [&](const std::string& message) { + CMVR_LOG(ERROR) << "[TouchScreenTask][START_REJECTED] " << message; + if (phase_ != Phase::FAILED) last_status_ = Status::ROBOT_COMMAND_FAILED; + phase_ = Phase::FAILED; + setCoordinateOverlayEnabled(true); + return false; + }; + cancelApproach(); + try { + if (arm_->isEmergencyStopped() || arm_->isProtectiveStopped()) { + return reject_start("safety stop active"); + } + if (!arm_->isConnected()) return reject_start("arm is not connected"); + const auto stopped = arm_->stopMotion(); + if (!stopped.ok()) return reject_start("stop failed: " + stopped.message); + const auto recovered = arm_->recoverSpeedLPlanningFault(); + if (!recovered.ok()) return reject_start(recovered.message); + } catch (const std::exception& error) { + return reject_start(error.what()); + } catch (...) { + return reject_start("unknown stop/recovery error"); + } + stopUnlocked(); - if (!moveToInitPositionBeforeStartIfEnabled()) { + if (!moveToInitPositionIfEnabled(config_.initialization().before_start(), true)) { return false; } @@ -455,35 +386,11 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) { target_u_ = u; target_v_ = v; - target_locked_ = false; - pbvs_target_initialized_ = false; - touch_command_started_ = false; - retract_command_started_ = false; - align_stable_count_ = 0; - align_debug_count_ = 0; - pbvs_debug_count_ = 0; - last_touch_pressure_sum_ = 0.0; - last_touch_resultant_fz_ = 0.0; - last_touch_nonzero_count_ = 0; - last_active_tag_id_ = -1; - last_align_error_screen_tag_.setZero(); - locked_target_rotation_valid_ = false; - locked_target_rotation_.setIdentity(); - touch_start_position_valid_ = false; - touch_start_position_base_.setZero(); - retract_start_position_valid_ = false; - retract_start_position_base_.setZero(); - have_last_T_B_G_ = false; - last_T_B_G_.setIdentity(); - max_T_B_G_translation_delta_m_ = 0.0; - max_T_B_G_rotation_delta_rad_ = 0.0; - phase_ = Phase::ALIGNING; + phase_ = config_.approach().enable() ? Phase::PREPARING : Phase::ALIGNING; setCoordinateOverlayEnabled(false); startCoordinateOverlayWorker(); - phase_after_retract_ = Phase::DONE; - final_status_after_retract_ = Status::DONE; phase_start_time_ = Clock::now(); - last_status_ = Status::ALIGN_WAITING_TRACK; + last_status_ = config_.approach().enable() ? Status::PREPARING : Status::ALIGN_WAITING_TRACK; return true; } @@ -504,6 +411,10 @@ bool TouchScreenTask::step(const double dt) { } switch (phase_) { + case Phase::PREPARING: + return stepPreparing(); + case Phase::APPROACHING: + return stepApproaching(); case Phase::IDLE: last_status_ = Status::IDLE; return true; @@ -520,7 +431,7 @@ bool TouchScreenTask::step(const double dt) { CMVR_LOG(WARNING) << "[TouchScreenTask][ALIGN_PAUSE_TIMEOUT]" << " elapsed_s=" << paused_s << ", timeout_s=" << config_.alignment().timeout_s() - << ", move_to_init=" << config_.initialization().after_finish(); + << ", move_to_init=" << config_.initialization().after_failure(); enterFailed(Status::ALIGN_TIMEOUT); return false; } @@ -701,6 +612,7 @@ void TouchScreenTask::stop() { } void TouchScreenTask::stopUnlocked() { + cancelApproach(); if (arm_) { try { arm_->stopL(); @@ -712,6 +624,11 @@ void TouchScreenTask::stopUnlocked() { phase_ = Phase::IDLE; setCoordinateOverlayEnabled(true); + resetRunState(); + last_status_ = Status::STOPPED; +} + +void TouchScreenTask::resetRunState() { phase_after_retract_ = Phase::DONE; final_status_after_retract_ = Status::DONE; target_locked_ = false; @@ -719,6 +636,8 @@ void TouchScreenTask::stopUnlocked() { touch_command_started_ = false; retract_command_started_ = false; align_stable_count_ = 0; + align_debug_count_ = 0; + pbvs_debug_count_ = 0; last_active_tag_id_ = -1; last_touch_pressure_sum_ = 0.0; last_touch_resultant_fz_ = 0.0; @@ -734,7 +653,7 @@ void TouchScreenTask::stopUnlocked() { last_T_B_G_.setIdentity(); max_T_B_G_translation_delta_m_ = 0.0; max_T_B_G_rotation_delta_rad_ = 0.0; - last_status_ = Status::STOPPED; + last_touch_pressure_log_time_ = Clock::time_point{}; } TouchScreenTask::Phase TouchScreenTask::phase() const { @@ -748,7 +667,8 @@ TouchScreenTask::Status TouchScreenTask::lastStatus() const { } bool TouchScreenTask::isBusyUnlocked() const { - return phase_ == Phase::ALIGNING || phase_ == Phase::ALIGN_REACHED || + return phase_ == Phase::PREPARING || phase_ == Phase::APPROACHING || + phase_ == Phase::ALIGNING || phase_ == Phase::ALIGN_REACHED || phase_ == Phase::TOUCHING || phase_ == Phase::DWELLING || phase_ == Phase::RETRACTING; } @@ -830,6 +750,8 @@ std::string TouchScreenTask::detailStatusString() const { const char* TouchScreenTask::phaseToString(const Phase phase) { switch (phase) { case Phase::IDLE: return "IDLE"; + case Phase::PREPARING: return "PREPARING"; + case Phase::APPROACHING: return "APPROACHING"; case Phase::ALIGNING: return "ALIGNING"; case Phase::ALIGN_REACHED: return "ALIGN_REACHED"; case Phase::TOUCHING: return "TOUCHING"; @@ -863,6 +785,10 @@ const char* TouchScreenTask::statusToString(const Status status) { case Status::ROBOT_STATE_FAILED: return "ROBOT_STATE_FAILED"; case Status::ROBOT_COMMAND_FAILED: return "ROBOT_COMMAND_FAILED"; case Status::TASK_BUSY: return "TASK_BUSY"; + case Status::PREPARING: return "PREPARING"; + case Status::APPROACHING: return "APPROACHING"; + case Status::APPROACH_FAILED: return "APPROACH_FAILED"; + case Status::APPROACH_TIMEOUT: return "APPROACH_TIMEOUT"; } return "UNKNOWN"; } @@ -965,6 +891,20 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& cmvr::common::math::toEigenVec6(pbvs.amax6()); const Eigen::Matrix4d T_H_P = toEigenMat4(calibration.hand_tag_to_tcp()); + const auto& approach = config.approach(); + if (approach.enable()) { + for (const double value : {approach.velocity(), approach.acceleration(), + approach.jerk(), approach.timeout_s()}) { + if (!std::isfinite(value) || value <= 0.0) return false; + } + if (!approach.has_minimum_clearance_m() || + !std::isfinite(approach.minimum_clearance_m()) || + approach.minimum_clearance_m() < 0.0 || + position_offset_G.z() <= approach.minimum_clearance_m()) { + return false; + } + } + if (screen_tag.id() < 0 || hand_tag.id() < 0 || screen_tag.id() == hand_tag.id() || !std::isfinite(screen_tag.size_m()) || screen_tag.size_m() <= 0.0 || @@ -1013,19 +953,20 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& return false; } - if (config.initialization().before_start() || config.initialization().after_finish()) { - std::vector init_joint_names; - init_joint_names.reserve(static_cast( - config.initialization().joint_positions_size())); - for (const auto& joint : config.initialization().joint_positions()) { - init_joint_names.push_back(joint.joint_name()); - } - std::vector init_positions; - if (!buildInitJointPositionsFromConfig(config, init_joint_names, init_positions) || - static_cast(init_positions.size()) != - config.initialization().joint_positions_size()) { + if (config.initialization().before_start() || config.initialization().after_finish() || + config.initialization().after_failure()) { + const auto& joints = config.initialization().joint_positions(); + if (joints.empty()) { return false; } + std::unordered_set names; + for (const auto& joint : joints) { + if (!joint.has_joint_name() || joint.joint_name().empty() || + !joint.has_rad() || !std::isfinite(joint.rad()) || + !names.insert(joint.joint_name()).second) { + return false; + } + } } const auto& initialization = config.initialization(); @@ -1040,10 +981,8 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& return false; } - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { + if (!isTactileRegionSupported(toFingerType(tactile.finger()), + toTactileRegion(tactile.region()))) { return false; } @@ -1103,10 +1042,6 @@ bool TouchScreenTask::applyConfig() { if (!perception_ || !external_perception_) { return false; } - if (!validateConfig(config_)) { - return false; - } - init_skip_position_tolerance_rad_ = config_.initialization().has_skip_position_tolerance_rad() ? config_.initialization().skip_position_tolerance_rad() @@ -1116,16 +1051,11 @@ bool TouchScreenTask::applyConfig() { ? config_.initialization().skip_velocity_tolerance_rad_s() : 1e-2; + const auto& tactile = config_.touch().tactile(); + tactile_region_ = {toFingerType(tactile.finger()), toTactileRegion(tactile.region())}; if (dexhand_) { - const auto& tactile = config_.touch().tactile(); - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { - return false; - } try { - dexhand_->setTactilePollingRegions(tactile_regions); + dexhand_->setTactilePollingRegion(tactile_region_.first, tactile_region_.second); } catch (...) { return false; } @@ -1177,41 +1107,180 @@ bool TouchScreenTask::applyConfig() { return true; } -bool TouchScreenTask::stepAligning(const double dt) { - const auto& alignment = config_.alignment(); - const auto target_orientation = - cmvr::common::math::toEigenEuler(alignment.target().hand_orientation_g()); - const auto& target = alignment.target(); - const Eigen::Vector3d position_offset_G = - target.has_position_offset_g() - ? cmvr::common::math::toEigenVec3(target.position_offset_g()) - : Eigen::Vector3d::Zero(); - const Eigen::Vector3d rotation_offset_G = - target.has_rotation_offset_g() - ? cmvr::common::math::toEigenVec3(target.rotation_offset_g()) - : Eigen::Vector3d::Zero(); +void TouchScreenTask::cancelApproach() { + if (approach_cancel_) approach_cancel_->store(true); + if (approach_motion_.valid()) { + // Safe to join under mutex_: the worker and its callbacks own no task state. + try { + (void)approach_motion_.get(); + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] " << error.what(); + } catch (...) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] unknown motion error"; + } + } + approach_cancel_.reset(); +} - const auto now = Clock::now(); - const double elapsed = std::chrono::duration(now - phase_start_time_).count(); - if (elapsed > alignment.timeout_s()) { +bool TouchScreenTask::stepPreparing() { + if (std::chrono::duration(Clock::now() - phase_start_time_).count() > + config_.alignment().timeout_s()) { + enterFailed(Status::APPROACH_TIMEOUT); + return false; + } + // Take the visual/FK snapshot only after the previous velocity motion stops. + if (arm_->busy()) return true; + + Eigen::Vector3d anchor_G; + if (!updateAlignmentAnchor(anchor_G) || !updateAlignmentTcpPose()) return true; + const Eigen::Matrix4d T_G_P = tcp_pose_tracker_.T_G_P(); + if (!updatePbvsTarget(anchor_G, T_G_P)) return false; + + try { + const Eigen::Matrix4d T_B_P = common::math::poseToMatrix(arm_->fk(true)); + const Eigen::Matrix4d T_B_G = T_B_P * T_G_P.inverse(); + const Eigen::Matrix4d target_B = T_B_G * pbvs_.targetPose(); + if (!isHomogeneousTransform(T_B_G) || !isHomogeneousTransform(target_B)) { + enterFailed(Status::ROBOT_STATE_FAILED); + return false; + } + + const auto& cfg = config_.approach(); + device::MotionOptions options; + options.velocity = cfg.velocity(); + options.acceleration = cfg.acceleration(); + options.jerk = cfg.jerk(); + const Eigen::Vector3d normal_B = T_B_G.block<3, 3>(0, 0).col(2); + const Eigen::Vector3d anchor_B = + T_B_G.block<3, 3>(0, 0) * anchor_G + T_B_G.block<3, 1>(0, 3); + // A fixed screen-plane constraint, including the start and the smoothed + // path. It guards TCP samples only, not the hand/arm's swept geometry. + options.is_tcp_pose_valid = + [normal_B, anchor_B, clearance = cfg.minimum_clearance_m()] + (const device::CartesianPose& pose) { + const Eigen::Vector3d p(pose.x, pose.y, pose.z); + return p.allFinite() && normal_B.dot(p - anchor_B) >= clearance; + }; + const auto target = common::math::matrixToPose(target_B); + if (!options.is_tcp_pose_valid(common::math::matrixToPose(T_B_P)) || + !options.is_tcp_pose_valid(target)) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] TCP start/target violates screen clearance"; + enterFailed(Status::APPROACH_FAILED); + return false; + } + + phase_start_time_ = Clock::now(); + const auto started = phase_start_time_; + const double timeout_s = cfg.timeout_s(); + approach_cancel_ = std::make_shared>(false); + options.cancellation_requested = [cancel = approach_cancel_, started, timeout_s] { + return cancel->load() || + std::chrono::duration(Clock::now() - started).count() >= timeout_s; + }; + approach_motion_ = std::async(std::launch::async, [arm = arm_, target, options, started, timeout_s] { + const auto result = arm->moveP(target, options, device::FrameType::Base); + // Record deadline failure on the worker, not on a potentially late + // TaskManager polling tick after successful completion. + return std::chrono::duration(Clock::now() - started).count() >= timeout_s + ? device::Result::failure(device::ArmErrorCode::Timeout, "approach timed out") + : result; + }); + phase_ = Phase::APPROACHING; + last_status_ = Status::APPROACHING; + CMVR_LOG(INFO) << "[TouchScreenTask][APPROACH_START] target_base=[" + << target.x << ", " << target.y << ", " << target.z + << "], velocity_rad_s=" << options.velocity; + return true; + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] " << error.what(); + enterFailed(Status::APPROACH_FAILED); + return false; + } +} + +bool TouchScreenTask::stepApproaching() { + const double elapsed = std::chrono::duration(Clock::now() - phase_start_time_).count(); + // The shared TaskManager thread never waits for planning or motion here. + if (approach_motion_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { + if (elapsed >= config_.approach().timeout_s()) { + approach_cancel_->store(true); + last_status_ = Status::APPROACH_TIMEOUT; + } + return true; + } + + try { + const auto result = approach_motion_.get(); + approach_cancel_.reset(); + if (!result.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH_FAILED] elapsed_s=" << elapsed + << ", error=" << result.message; + enterFailed(result.code == device::ArmErrorCode::Timeout + ? Status::APPROACH_TIMEOUT : Status::APPROACH_FAILED); + return false; + } + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH_FAILED] " << error.what(); + enterFailed(Status::APPROACH_FAILED); + return false; + } + + // Keep the original screen anchor and desired pose, but reacquire the live + // TCP pose and start PBVS with zero command history and its own timeout. + tcp_pose_tracker_.clear(); + pbvs_.resetTwistCommandState(); + align_stable_count_ = 0; + phase_ = Phase::ALIGNING; + phase_start_time_ = Clock::now(); + last_status_ = Status::ALIGN_WAITING_TRACK; + CMVR_LOG(INFO) << "[TouchScreenTask][APPROACH_DONE] elapsed_s=" << elapsed; + return true; +} + +bool TouchScreenTask::stepAligning(const double dt) { + const double elapsed = + std::chrono::duration(Clock::now() - phase_start_time_).count(); + if (elapsed > config_.alignment().timeout_s()) { enterFailed(Status::ALIGN_TIMEOUT); return false; } - const double pbvs_dt = std::clamp(dt, 0.0001, 0.05); + Eigen::Vector3d p_target_G = Eigen::Vector3d::Zero(); + // Missing perception is temporary: the helpers stop PBVS and record the + // waiting status, while step() keeps the alignment phase active. + if (!updateAlignmentAnchor(p_target_G) || !updateAlignmentTcpPose()) { + return true; + } + + const Eigen::Matrix4d& T_G_P = tcp_pose_tracker_.T_G_P(); + if (!updatePbvsTarget(p_target_G, T_G_P)) { + return false; + } + PbvsController::Output output; + if (!pbvs_.compute(T_G_P, std::clamp(dt, 0.0001, 0.05), output)) { + enterFailed(Status::ALIGN_COMPUTE_FAILED); + return false; + } + + device::CartesianVelocity twist_B; + if (!mapAlignmentCommandToBase(T_G_P, output, twist_B)) { + return false; + } + return applyAlignmentCommand(output, twist_B); +} + +bool TouchScreenTask::updateAlignmentAnchor(Eigen::Vector3d& p_target_G) { // The hand camera is only needed to establish the target anchor once. // After the first successful PBVS target initialization, tracker_ keeps // that anchor fixed and the external camera supplies the live TCP pose. const bool hand_camera_needed = !target_locked_ || !pbvs_target_initialized_; - bool hand_perception_ok = true; if (hand_camera_needed) { perception::AprilTagPerception::Options hand_options; hand_options.depth_policy = toDepthPolicy(config_.perception().hand_camera().depth_policy()); hand_options.detect_tags = true; hand_options.fetch_encoded = false; - hand_perception_ok = perception_->update(hand_options); - if (!hand_perception_ok) { + if (!perception_->update(hand_options)) { if (align_debug_count_ == 0 && !perception_->color().empty()) { cv::imwrite("/tmp/cmvr_hand_camera_perception.png", perception_->color()); } @@ -1231,7 +1300,7 @@ bool TouchScreenTask::stepAligning(const double dt) { } stopPbvsMotion(); last_status_ = Status::ALIGN_WAITING_PERCEPTION; - return true; + return false; } } @@ -1243,7 +1312,7 @@ bool TouchScreenTask::stepAligning(const double dt) { pbvs_target_initialized_ = false; align_stable_count_ = 0; } - } else if (hand_camera_needed && hand_perception_ok) { + } else if (hand_camera_needed) { tracking_ok = tracker_.track(); } @@ -1264,42 +1333,37 @@ bool TouchScreenTask::stepAligning(const double dt) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } const int tag_id = tracker_.activeTagId(); last_active_tag_id_ = tag_id; const int screen_tag_id = config_.perception().tags().screen().id(); - if (tag_id != screen_tag_id) { + if (tag_id != screen_tag_id || !tracker_.getAnchorInTag(tag_id, p_target_G)) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } - Eigen::Vector3d p_target_G = Eigen::Vector3d::Zero(); - if (!tracker_.getAnchorInTag(tag_id, p_target_G)) { - stopPbvsMotion(); - align_stable_count_ = 0; - last_status_ = Status::ALIGN_WAITING_TRACK; - return true; - } + return true; +} +bool TouchScreenTask::updateAlignmentTcpPose() { perception::AprilTagPerception::Options external_options; external_options.depth_policy = perception::AprilTagPerception::DepthPolicy::NONE; external_options.detect_tags = true; external_options.fetch_encoded = false; - if (!external_perception_->update(external_options)) { - publishCoordinateOverlay(); + const bool perception_ok = external_perception_->update(external_options); + publishCoordinateOverlay(); + if (!perception_ok) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_PERCEPTION; - return true; + return false; } - publishCoordinateOverlay(); - - tcp_pose_tracker_.setScreenTagId(screen_tag_id); + tcp_pose_tracker_.setScreenTagId(config_.perception().tags().screen().id()); if (!tcp_pose_tracker_.update(T_H_P_)) { if (align_debug_count_ == 0 && !external_perception_->color().empty()) { cv::imwrite("/tmp/cmvr_external_camera_perception.png", @@ -1325,10 +1389,27 @@ bool TouchScreenTask::stepAligning(const double dt) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } - const Eigen::Matrix4d& T_G_P = tcp_pose_tracker_.T_G_P(); + return true; +} + +bool TouchScreenTask::updatePbvsTarget(const Eigen::Vector3d& p_target_G, + const Eigen::Matrix4d& T_G_P) { + const auto& alignment = config_.alignment(); + const auto target_orientation = + cmvr::common::math::toEigenEuler(alignment.target().hand_orientation_g()); + const auto& target = alignment.target(); + const Eigen::Vector3d position_offset_G = + target.has_position_offset_g() + ? cmvr::common::math::toEigenVec3(target.position_offset_g()) + : Eigen::Vector3d::Zero(); + const Eigen::Vector3d rotation_offset_G = + target.has_rotation_offset_g() + ? cmvr::common::math::toEigenVec3(target.rotation_offset_g()) + : Eigen::Vector3d::Zero(); + const Eigen::Matrix3d R_G_H_target = rotationFromTargetEuler(target_orientation.x(), target_orientation.y(), @@ -1379,12 +1460,12 @@ bool TouchScreenTask::stepAligning(const double dt) { pbvs_target_initialized_ = true; } - PbvsController::Output output; - if (!pbvs_.compute(T_G_P, pbvs_dt, output)) { - enterFailed(Status::ALIGN_COMPUTE_FAILED); - return false; - } + return true; +} +bool TouchScreenTask::mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P, + const PbvsController::Output& output, + device::CartesianVelocity& twist_B) { Eigen::Matrix4d T_B_P = Eigen::Matrix4d::Identity(); try { T_B_P = cmvr::common::math::poseToMatrix(arm_->fk(true)); @@ -1426,7 +1507,7 @@ bool TouchScreenTask::stepAligning(const double dt) { return false; } - const device::CartesianVelocity twist_B{ + twist_B = { linear_B.x(), linear_B.y(), linear_B.z(), angular_B.x(), angular_B.y(), angular_B.z()}; @@ -1501,6 +1582,11 @@ bool TouchScreenTask::stepAligning(const double dt) { << twist_B.wx << ' ' << twist_B.wy << ' ' << twist_B.wz << ']'; } + return true; +} + +bool TouchScreenTask::applyAlignmentCommand(const PbvsController::Output& output, + const device::CartesianVelocity& twist_B) { last_align_error_screen_tag_ = output.position_error_G; if (output.reached) { ++align_stable_count_; @@ -1508,8 +1594,8 @@ bool TouchScreenTask::stepAligning(const double dt) { align_stable_count_ = 0; } - if (align_stable_count_ >= alignment.stable_frames()) { - CMVR_LOG(INFO) << "[TouchScreenTask][ALIGN_REACHED] tag_id=" << tag_id + if (align_stable_count_ >= config_.alignment().stable_frames()) { + CMVR_LOG(INFO) << "[TouchScreenTask][ALIGN_REACHED] tag_id=" << last_active_tag_id_ << ", err_xyz_G=[" << output.position_error_G.x() << ", " << output.position_error_G.y() << ", " << output.position_error_G.z() << "]" @@ -1588,7 +1674,7 @@ bool TouchScreenTask::stepTouching() { << ", fz_N=" << last_touch_resultant_fz_ << ", criterion_value_N=" << last_touch_pressure_sum_ << ", threshold_N=" << config_.touch().tactile().force_threshold() - << "; check preceding CartesianVelocityController/planner errors"; + << "; check preceding SpeedLExecutor/planner errors"; enterFailed(Status::ROBOT_COMMAND_FAILED); return false; } @@ -1727,6 +1813,9 @@ bool TouchScreenTask::stepRetracting() { const bool have_final_position = readCurrentTouchPointPositionBase(final_position_base); Eigen::Vector3d final_delta_base = Eigen::Vector3d::Zero(); const bool have_final_delta = retract_start_position_valid_ && have_final_position; + const bool return_to_init = phase_after_retract_ == Phase::FAILED + ? config_.initialization().after_failure() + : config_.initialization().after_finish(); if (have_final_delta) { final_delta_base = final_position_base - retract_start_position_base_; max_forward_after_retract_m_ = std::max(max_forward_after_retract_m_, @@ -1736,7 +1825,7 @@ bool TouchScreenTask::stepRetracting() { CMVR_LOG(INFO) << "[TouchScreenTask][RETRACT_DONE] elapsed=" << elapsed << ", target_distance_m=" << retract_distance_m << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0 - << ", move_to_init=" << (config_.initialization().after_finish() ? 1 : 0) + << ", move_to_init=" << return_to_init << ", final_tcp_delta_base=[" << final_delta_base.x() << ", " << final_delta_base.y() << ", " << final_delta_base.z() << "], final_tcp_dist=" << final_delta_base.norm(); @@ -1744,10 +1833,15 @@ bool TouchScreenTask::stepRetracting() { CMVR_LOG(INFO) << "[TouchScreenTask][RETRACT_DONE] elapsed=" << elapsed << ", target_distance_m=" << retract_distance_m << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0 - << ", move_to_init=" << (config_.initialization().after_finish() ? 1 : 0) + << ", move_to_init=" << return_to_init << ", final_tcp_delta_base=unavailable"; } + if (phase_after_retract_ == Phase::FAILED) { + enterFailed(final_status_after_retract_); + return false; + } + // Stop the retract worker synchronously before switching to the final // joint-position trajectory. stopL() only requests deceleration and can // return while the worker still owns the velocity-control mode. @@ -1756,8 +1850,7 @@ bool TouchScreenTask::stepRetracting() { enterFailed(Status::ROBOT_COMMAND_FAILED); return false; } - if ((phase_after_retract_ == Phase::DONE || phase_after_retract_ == Phase::FAILED) && - !moveToInitPositionIfEnabled()) { + if (phase_after_retract_ == Phase::DONE && !moveToInitPositionIfEnabled(return_to_init)) { phase_ = Phase::FAILED; last_status_ = Status::ROBOT_COMMAND_FAILED; return false; @@ -1797,7 +1890,7 @@ void TouchScreenTask::logTouchingSpeedLState() const { return; } - const Eigen::Matrix cmd_twist_base = toEigen6(arm_->getSpeedLCommandTwistBase()); + const Eigen::Matrix cmd_twist_base = cmvr::common::math::velocityToVector(arm_->getSpeedLCommandTwistBase()); Eigen::Vector3d current_position_base = Eigen::Vector3d::Zero(); const bool have_current_position = readCurrentTouchPointPositionBase(current_position_base); const bool have_delta = touch_start_position_valid_ && have_current_position; @@ -1834,6 +1927,7 @@ bool TouchScreenTask::buildInitJointPositions(std::vector& positions_out config_, arm_->getRobotModel().joint_names, positions_out); } +// Skip initialization only if both joint position and measured velocity are settled. bool TouchScreenTask::isAtInitPosition(const std::vector& positions) const { if (!arm_ || arm_->busy()) { return false; @@ -1855,8 +1949,8 @@ bool TouchScreenTask::isAtInitPosition(const std::vector& positions) con return true; } -bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { - if (!config_.initialization().before_start()) { +bool TouchScreenTask::moveToInitPositionIfEnabled(const bool enabled, const bool use_move_j) { + if (!enabled) { return true; } if (!arm_) { @@ -1870,8 +1964,9 @@ bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { return false; } + const char* motion = use_move_j ? "moveJ" : "moveP"; if (isAtInitPosition(init_positions)) { - CMVR_LOG(INFO) << "[TouchScreenTask] initial position already reached; skipping moveJ" + CMVR_LOG(INFO) << "[TouchScreenTask] initial position already reached; skipping " << motion << ", arm=" << id_; return true; } @@ -1880,40 +1975,15 @@ bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { device::MotionOptions options; options.velocity = config_.initialization().velocity(); options.acceleration = config_.initialization().acceleration(); - const auto result = arm_->moveJ(init_cmd, options); + const auto result = use_move_j ? arm_->moveJ(init_cmd, options) : arm_->moveP(init_cmd, options); if (!result.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][RETURN_TO_INIT] " << motion << " failed: " << result.message; last_status_ = Status::ROBOT_COMMAND_FAILED; return false; } return true; } -bool TouchScreenTask::moveToInitPositionIfEnabled() const { - if (!config_.initialization().after_finish()) { - return true; - } - std::vector init_positions; - if (!arm_ || !buildInitJointPositions(init_positions)) { - return false; - } - - if (isAtInitPosition(init_positions)) { - CMVR_LOG(INFO) << "[TouchScreenTask] final initial position already reached; skipping moveJ" - << ", arm=" << id_; - return true; - } - - device::JointPositionCommand init_cmd{init_positions}; - device::MotionOptions options; - options.velocity = config_.initialization().velocity(); - options.acceleration = config_.initialization().acceleration(); - const auto result = arm_->moveJ(init_cmd, options); - if (!result.ok()) { - return false; - } - return true; -} - bool TouchScreenTask::handleTouchTriggered(const bool stop_forward_motion) { if (config_.touch().dwell_time_s() <= 0.0) { // Submit reversal in this tick, before any synchronous FK or logging. @@ -1966,7 +2036,7 @@ bool TouchScreenTask::startTouchPhase() { options.acceleration = speed_l.acceleration(); if (speed_l.has_linear_jerk()) options.linear_jerk = speed_l.linear_jerk(); options.continuous_linear_reversal = true; - const auto result = arm_->speedL(toCartesianVelocity( + const auto result = arm_->speedL(cmvr::common::math::vectorToVelocity( cmvr::common::math::toEigenVec6(speed_l.twist_tool())), options, 0.0, @@ -2003,7 +2073,7 @@ bool TouchScreenTask::startTouchPhase() { return false; } - if (!moveToInitPositionIfEnabled()) { + if (!moveToInitPositionIfEnabled(config_.initialization().after_finish())) { last_status_ = Status::ROBOT_COMMAND_FAILED; return false; } @@ -2027,7 +2097,7 @@ bool TouchScreenTask::startRetractPhase(const Phase next_phase_after_retract, retract_start_position_valid_ = false; retract_direction_base_.setZero(); max_forward_after_retract_m_ = 0.0; - const auto retract_cmd = toCartesianVelocity( + const auto retract_cmd = cmvr::common::math::vectorToVelocity( cmvr::common::math::toEigenVec6(retract.twist_tool())); device::SpeedLOptions options; options.acceleration = retract.acceleration(); @@ -2060,7 +2130,8 @@ bool TouchScreenTask::startRetractPhase(const Phase next_phase_after_retract, } void TouchScreenTask::enterFailed(const Status status) { - stopPbvsMotion(); + cancelApproach(); + pbvs_.resetTwistCommandState(); if (phase_ == Phase::RETRACTING && retract_start_position_valid_) { CMVR_LOG(WARNING) << "[TouchScreenTask][RETRACT_FAILED] status=" << statusToString(status) << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0; @@ -2069,7 +2140,34 @@ void TouchScreenTask::enterFailed(const Status status) { setCoordinateOverlayEnabled(true); touch_command_started_ = false; retract_command_started_ = false; - last_status_ = moveToInitPositionIfEnabled() ? status : Status::ROBOT_COMMAND_FAILED; + last_status_ = status; + if (!arm_) return; + + try { + // stopL only requests deceleration. Confirm the velocity worker has + // stopped before allowing a joint-position return after a failure. + const auto stopped = arm_->stopMotion(); + if (!stopped.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_SKIPPED] status=" + << statusToString(status) << ", stop failed: " << stopped.message; + return; + } + if (!config_.initialization().after_failure()) return; + if (arm_->isEmergencyStopped() || arm_->isProtectiveStopped()) { + CMVR_LOG(WARNING) << "[TouchScreenTask][FAILURE_RETURN_SKIPPED] safety stop active" + << ", status=" << statusToString(status); + return; + } + CMVR_LOG(INFO) << "[TouchScreenTask][FAILURE_RETURN_START] status=" << statusToString(status); + const bool returned = moveToInitPositionIfEnabled(true); + CMVR_LOG(INFO) << "[TouchScreenTask][FAILURE_RETURN_DONE] success=" << returned + << ", status=" << statusToString(status); + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_FAILED] " << error.what(); + } catch (...) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_FAILED] unknown error"; + } + last_status_ = status; } bool TouchScreenTask::updateTouchPressure() { @@ -2080,31 +2178,16 @@ bool TouchScreenTask::updateTouchPressure() { return false; } - const auto& tactile = config_.touch().tactile(); - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { - return false; - } - - double resultant_value = 0.0; - double resultant_fz = 0.0; try { - for (const auto& tactile_region : tactile_regions) { - const auto resultant_force = dexhand_->getResultantForceNewtons( - tactile_region.first, tactile_region.second); - resultant_value += tactileForceValue(resultant_force, tactile.criterion()); - resultant_fz += resultant_force.fz; - } + const auto force = dexhand_->getResultantForceNewtons( + tactile_region_.first, tactile_region_.second); + last_touch_pressure_sum_ = tactileForceValue(force, config_.touch().tactile().criterion()); + last_touch_resultant_fz_ = force.fz; + last_touch_nonzero_count_ = std::abs(last_touch_pressure_sum_) > 1e-9 ? 1 : 0; + return true; } catch (...) { return false; } - - last_touch_nonzero_count_ = std::abs(resultant_value) > 1e-9 ? 1 : 0; - last_touch_pressure_sum_ = resultant_value; - last_touch_resultant_fz_ = resultant_fz; - return true; } void TouchScreenTask::logTouchPressure(const bool force) { diff --git a/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp b/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp index 7098140c..2363bf46 100644 --- a/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp +++ b/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,8 @@ #include #include "task/touch_screen_task/include/touch_screen_task.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "algorithms/planner/joint/joint_path_planner_factory.h" #include "common/config/config_files.h" #include "common/vision/image_projection.h" @@ -154,6 +157,164 @@ cmvr::config::TouchScreenTaskConfig loadMujocoTouchConfig(const std::filesystem: return root_config.touch_screen_task(); } +class FailureReturnCamera final : public cmvr::device::AbstractCamera { +public: + std::string typeName() const override { return "FailureReturnCamera"; } + void getState(cmvr::device::CameraState& state) override { state = {}; } +}; + +class FailureReturnArm final : public cmvr::device::RobotArm { +public: + using Result = cmvr::device::Result; + explicit FailureReturnArm(const cmvr::config::TouchScreenTaskConfig& config) { + for (const auto& joint : config.initialization().joint_positions()) { + model.joint_names.push_back(joint.joint_name()); + state.position.push_back(joint.rad() + 0.1); + state.velocity.push_back(0.0); + } + model.dof = model.joint_names.size(); + } + + std::string typeName() const override { return "FailureReturnArm"; } + cmvr::RobotModel getRobotModel() const override { return model; } + std::size_t getDof() const override { return model.dof; } + cmvr::device::ArmState getRobotState() const override { return {}; } + cmvr::device::JointGroupState getJointState() const override { return state; } + cmvr::device::CartesianPose getTcpPose(cmvr::device::FrameType) const override { return {}; } + cmvr::device::RobotMode getRobotMode() const override { return cmvr::device::RobotMode::Idle; } + cmvr::device::SafetyMode getSafetyMode() const override { + return emergency ? cmvr::device::SafetyMode::EmergencyStop + : protective ? cmvr::device::SafetyMode::ProtectiveStop + : cmvr::device::SafetyMode::Normal; + } + cmvr::device::ControlMode getControlMode() const override { return cmvr::device::ControlMode::Position; } + bool isProtectiveStopped() const override { return protective; } + bool isEmergencyStopped() const override { return emergency; } + bool isFault() const override { return planning_fault; } + bool isConnected() const override { return connected; } + bool busy() const override { return false; } + double getSpeedScaling() const override { return 1.0; } + + Result stopL(std::optional) override { return Result::success(); } + Result stopMotion() override { + calls.push_back("stopMotion"); + return stop_result; + } + Result recoverSpeedLPlanningFault() override { + calls.push_back("recoverSpeedLPlanningFault"); + if (recovery_result.ok()) planning_fault = false; + return recovery_result; + } + Result moveP(const cmvr::device::JointPositionCommand& target, + const cmvr::device::MotionOptions& options) override { + calls.push_back("moveP"); + return_target = target.position; + return_options = options; + return move_result; + } + Result moveJ(const cmvr::device::JointPositionCommand& target, + const cmvr::device::MotionOptions& options) override { + calls.push_back("moveJ"); + startup_target = target.position; + startup_options = options; + return move_result; + } + + Result torqueOn() override { return unsupported(); } + Result moveP(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&, + cmvr::device::FrameType) override { return unsupported(); } + Result torqueOff() override { return unsupported(); } + Result calibrateZeroQ(const std::string&) override { return unsupported(); } + Result emergencyStop() override { return unsupported(); } + Result protectiveStop() override { return unsupported(); } + Result recoverProtectiveStop(const cmvr::device::JointTrajectory&, + const cmvr::device::MotionOptions&) override { return unsupported(); } + Result setSpeedScaling(double) override { return unsupported(); } + Result speedJ(const cmvr::device::JointVelocityCommand&, double, double) override { return unsupported(); } + Result stopJ(double) override { return unsupported(); } + Result moveL(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&, + cmvr::device::FrameType) override { return unsupported(); } + Result speedL(const cmvr::device::CartesianVelocity&, double, double, + cmvr::device::FrameType) override { return unsupported(); } + Result startServoMode(const cmvr::device::ServoOptions&) override { return unsupported(); } + Result servoJ(const cmvr::device::JointPositionCommand&) override { return unsupported(); } + Result servoL(const cmvr::device::CartesianPose&, cmvr::device::FrameType) override { return unsupported(); } + Result servoSpeedJ(const cmvr::device::JointVelocityCommand&) override { return unsupported(); } + Result servoSpeedL(const cmvr::device::CartesianVelocity&, cmvr::device::FrameType) override { return unsupported(); } + Result stopServoMode() override { return unsupported(); } + Result connect(const std::string&, int) override { return unsupported(); } + Result disconnect() override { return unsupported(); } + Result powerOn() override { return unsupported(); } + Result powerOff() override { return unsupported(); } + Result brakeRelease() override { return unsupported(); } + Result shutdown() override { return unsupported(); } + Result clearFault() override { return unsupported(); } + Result unlockProtectiveStop() override { return unsupported(); } + Result loadProgram(const std::string&) override { return unsupported(); } + Result playProgram() override { return unsupported(); } + Result pauseProgram() override { return unsupported(); } + Result stopProgram() override { return unsupported(); } + std::vector ik(const std::string&, const std::string&, + const cmvr::device::CartesianPose&) override { return {}; } + std::shared_ptr kinematicsSolver() const override { return nullptr; } + cmvr::device::CartesianPose fk(const std::string&, const std::string&) override { return {}; } + cmvr::device::CartesianPose fk(bool) override { return {}; } + cmvr::device::CartesianVelocity getSpeedLCommandTwistBase() const override { return {}; } + + cmvr::RobotModel model; + cmvr::device::JointGroupState state; + Result stop_result{Result::success()}; + Result move_result{Result::success()}; + Result recovery_result{Result::success()}; + bool planning_fault{false}; + bool connected{true}; + bool emergency{false}; + bool protective{false}; + std::vector calls; + std::vector return_target; + cmvr::device::MotionOptions return_options; + std::vector startup_target; + cmvr::device::MotionOptions startup_options; + +private: + static Result unsupported() { + ADD_FAILURE() << "unexpected robot command in failure-return test"; + return Result::failure(cmvr::device::ArmErrorCode::UnsupportedCommand, "not used"); + } +}; + +class TouchScreenFailureReturnTest : public ::testing::Test { +protected: + void SetUp() override { + config = loadMujocoTouchConfig(findProjectRoot()); + config.mutable_approach()->set_enable(false); + config.mutable_initialization()->set_before_start(false); + config.mutable_initialization()->set_after_finish(true); + // Trigger the shared failure handler via public APIs, without camera input. + config.mutable_alignment()->set_timeout_s(1e-9); + arm = std::make_shared(config); + } + + void expectTimeoutFailure() { + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + EXPECT_FALSE(task.step(0.02)); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(task.isFailed()); + EXPECT_FALSE(task.isFinished()); + EXPECT_FALSE(task.isBusy()); + const auto calls = arm->calls; + EXPECT_FALSE(task.step(0.02)); + EXPECT_EQ(arm->calls, calls) << "failure return must run only once"; + } + + cmvr::config::TouchScreenTaskConfig config; + std::shared_ptr arm; +}; + cmvr::device::DeviceManager& getTestDeviceManager() { static bool initialized = [] { cmvr::ConfigHelper::setConfigRootFromFile("cmvr-es/config/cmvr_es.pb.txt"); @@ -257,12 +418,188 @@ void run_touch_once(int u, int v) { } // namespace +TEST_F(TouchScreenFailureReturnTest, FailureReturnIsOptionalAndIndependentOfSuccessReturn) { + for (const bool explicitly_disabled : {false, true}) { + SCOPED_TRACE(explicitly_disabled); + config.mutable_initialization()->clear_after_failure(); + if (explicitly_disabled) config.mutable_initialization()->set_after_failure(false); + EXPECT_FALSE(config.initialization().after_failure()); + arm->calls.clear(); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } +} + +TEST_F(TouchScreenFailureReturnTest, EnabledFailureReturnStopsBeforeMovingAndPreservesFailure) { + config.mutable_initialization()->set_after_finish(false); + config.mutable_initialization()->set_after_failure(true); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); + std::vector expected_target; + for (const auto& joint : config.initialization().joint_positions()) { + expected_target.push_back(joint.rad()); + } + EXPECT_EQ(arm->return_target, expected_target); + EXPECT_DOUBLE_EQ(arm->return_options.velocity, config.initialization().velocity()); + EXPECT_DOUBLE_EQ(arm->return_options.acceleration, config.initialization().acceleration()); +} + +TEST_F(TouchScreenFailureReturnTest, InitializationStopsBeforeMoveJ) { + config.mutable_initialization()->set_before_start(true); + const auto camera = std::make_shared(); + cmvr::task::TouchScreenTask task(config); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault", "moveJ"})); + std::vector expected_target; + for (const auto& joint : config.initialization().joint_positions()) { + expected_target.push_back(joint.rad()); + } + EXPECT_EQ(arm->startup_target, expected_target); + EXPECT_DOUBLE_EQ(arm->startup_options.velocity, config.initialization().velocity()); + EXPECT_DOUBLE_EQ(arm->startup_options.acceleration, config.initialization().acceleration()); + + task.stop(); + arm->calls.clear(); + arm->stop_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected stop failure"); + EXPECT_FALSE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); +} + +TEST_F(TouchScreenFailureReturnTest, FailedStopOrSafetyStopPreventsFailureReturn) { + config.mutable_initialization()->set_after_failure(true); + for (const auto* reason : {"failed_stop", "emergency", "protective"}) { + SCOPED_TRACE(reason); + arm->stop_result = cmvr::device::Result::success(); + arm->emergency = false; + arm->protective = false; + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + arm->stop_result = std::string(reason) == "failed_stop" + ? cmvr::device::Result::failure(cmvr::device::ArmErrorCode::CommandFailed, + "injected stop failure") + : cmvr::device::Result::success(); + arm->emergency = std::string(reason) == "emergency"; + arm->protective = std::string(reason) == "protective"; + EXPECT_FALSE(task.step(0.02)); + EXPECT_TRUE(task.isFailed()); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } +} + +TEST_F(TouchScreenFailureReturnTest, NextRunRecoversPlanningFaultBeforeInitialization) { + config.mutable_initialization()->set_before_start(true); + config.mutable_initialization()->set_after_failure(true); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + arm->planning_fault = true; + + EXPECT_FALSE(task.step(0.02)); + ASSERT_TRUE(task.isFailed()); + ASSERT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(arm->isFault()) << "failure return must retain the original fault"; + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); + + arm->calls.clear(); + ASSERT_TRUE(task.touch(350, 260)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault", "moveJ"})); + EXPECT_FALSE(arm->isFault()); + EXPECT_TRUE(task.isBusy()); + EXPECT_FALSE(task.isFailed()); +} + +TEST_F(TouchScreenFailureReturnTest, DisabledInitializationStillRecoversBeforeStarting) { + config.mutable_initialization()->set_before_start(false); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + arm->planning_fault = true; + ASSERT_TRUE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault"})); + EXPECT_FALSE(arm->isFault()); + EXPECT_TRUE(task.isBusy()); +} + +TEST_F(TouchScreenFailureReturnTest, RejectedRestartPreservesPreviousFailureAndDoesNotMove) { + config.mutable_initialization()->set_before_start(true); + config.mutable_initialization()->set_after_failure(false); + for (const auto* reason : {"failed_stop", "fatal_fault", "emergency", "protective", "disconnected"}) { + SCOPED_TRACE(reason); + arm = std::make_shared(config); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + ASSERT_FALSE(task.step(0.02)); + ASSERT_TRUE(task.isFailed()); + ASSERT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + arm->calls.clear(); + const std::string failure = reason; + arm->planning_fault = true; + arm->emergency = failure == "emergency"; + arm->protective = failure == "protective"; + arm->connected = failure != "disconnected"; + if (failure == "failed_stop") { + arm->stop_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected stop failure"); + } + if (failure == "fatal_fault") { + arm->recovery_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected nonrecoverable fault"); + } + + EXPECT_FALSE(task.touch(350, 260)); + EXPECT_TRUE(task.isFailed()); + EXPECT_FALSE(task.isBusy()); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(arm->isFault()); + if (failure == "fatal_fault") { + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault"})); + } else if (failure == "failed_stop") { + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } else { + EXPECT_TRUE(arm->calls.empty()); + } + } +} + +TEST_F(TouchScreenFailureReturnTest, FailedReturnPreservesOriginalFailure) { + config.mutable_initialization()->set_after_failure(true); + arm->move_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected return failure"); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); +} + +TEST(TouchScreenTaskTest, FailureReturnRequiresValidInitialJointPositions) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + config.mutable_initialization()->set_before_start(false); + config.mutable_initialization()->set_after_finish(false); + config.mutable_initialization()->set_after_failure(true); + config.mutable_initialization()->clear_joint_positions(); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); +} + TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) { const auto project_root = findProjectRoot(); ASSERT_FALSE(project_root.empty()); for (const auto* file_name : {"touch_screen_task.pb.txt", "touch_screen_task_mujoco.pb.txt"}) { + SCOPED_TRACE(file_name); cmvr::config::TouchScreenTaskRootConfig root_config; const auto config_path = project_root / "cmvr-es/config/tasks/touch_screen_task" / file_name; @@ -271,39 +608,164 @@ TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) { const auto& config = root_config.touch_screen_task(); EXPECT_TRUE(config.has_initialization()); + EXPECT_TRUE(config.initialization().after_failure()); EXPECT_TRUE(config.has_perception()); ASSERT_TRUE(config.perception().has_tags()); - EXPECT_EQ(config.perception().tags().screen().id(), 1); - EXPECT_EQ(config.perception().tags().hand().id(), 0); - EXPECT_DOUBLE_EQ(config.perception().tags().screen().size_m(), 0.03); - EXPECT_DOUBLE_EQ(config.perception().tags().hand().size_m(), 0.03); + const auto& tags = config.perception().tags(); + EXPECT_GE(tags.screen().id(), 0); + EXPECT_GE(tags.hand().id(), 0); + EXPECT_NE(tags.screen().id(), tags.hand().id()); + EXPECT_GT(tags.screen().size_m(), 0.0); + EXPECT_GT(tags.hand().size_m(), 0.0); EXPECT_TRUE(config.perception().has_hand_camera()); const bool is_mujoco = std::string(file_name).find("mujoco") != std::string::npos; - EXPECT_EQ(config.devices().camera_id(), - is_mujoco ? "mujoco_hand_cam" : "right_hand_cam"); - EXPECT_EQ(config.devices().external_camera_id(), - is_mujoco ? "mujoco_external_touch_cam" : "cam5"); + EXPECT_FALSE(config.devices().camera_id().empty()); + EXPECT_FALSE(config.devices().external_camera_id().empty()); EXPECT_TRUE(config.has_alignment()); ASSERT_TRUE(config.alignment().has_calibration()); EXPECT_TRUE(config.alignment().calibration().has_hand_tag_to_tcp()); ASSERT_TRUE(config.alignment().target().has_hand_orientation_g()); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().rx(), 0.0); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().ry(), 0.0); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().rz(), - 3.141592653589793); + const auto& orientation = config.alignment().target().hand_orientation_g(); + EXPECT_TRUE(std::isfinite(orientation.rx())); + EXPECT_TRUE(std::isfinite(orientation.ry())); + EXPECT_TRUE(std::isfinite(orientation.rz())); ASSERT_TRUE(config.alignment().has_pbvs()); const auto& pbvs = config.alignment().pbvs(); - EXPECT_DOUBLE_EQ(pbvs.position_gain().x(), 2.0); - EXPECT_DOUBLE_EQ(pbvs.rotation_gain().z(), 1.5); - EXPECT_DOUBLE_EQ(pbvs.vmax6().z(), 0.05); - EXPECT_DOUBLE_EQ(pbvs.amax6().rz(), 2.0); - EXPECT_DOUBLE_EQ(pbvs.twist_filter_alpha(), 1.0); + EXPECT_GE(pbvs.position_gain().x(), 0.0); + EXPECT_GE(pbvs.rotation_gain().z(), 0.0); + EXPECT_GT(pbvs.vmax6().z(), 0.0); + EXPECT_GE(pbvs.amax6().rz(), 0.0); + EXPECT_GE(pbvs.twist_filter_alpha(), 0.0); + EXPECT_LE(pbvs.twist_filter_alpha(), 1.0); + if (is_mujoco) { + ASSERT_TRUE(config.has_approach()); + const auto& approach = config.approach(); + EXPECT_TRUE(approach.enable()); + EXPECT_DOUBLE_EQ(approach.velocity(), 0.65); + EXPECT_DOUBLE_EQ(approach.acceleration(), 1.7); + EXPECT_DOUBLE_EQ(approach.jerk(), 30.0); + EXPECT_DOUBLE_EQ(approach.timeout_s(), 10.0); + EXPECT_DOUBLE_EQ(approach.minimum_clearance_m(), 0.01); + EXPECT_DOUBLE_EQ(config.alignment().target().position_offset_g().z(), 0.05); + EXPECT_EQ(tags.screen().id(), 1); + EXPECT_EQ(tags.hand().id(), 0); + EXPECT_DOUBLE_EQ(tags.screen().size_m(), 0.03); + EXPECT_DOUBLE_EQ(tags.hand().size_m(), 0.03); + EXPECT_EQ(config.devices().camera_id(), "mujoco_hand_cam"); + EXPECT_EQ(config.devices().external_camera_id(), "mujoco_external_touch_cam"); + EXPECT_DOUBLE_EQ(orientation.rx(), 0.0); + EXPECT_DOUBLE_EQ(orientation.ry(), 0.0); + EXPECT_DOUBLE_EQ(orientation.rz(), 3.141592653589793); + EXPECT_DOUBLE_EQ(pbvs.position_gain().x(), 2.0); + EXPECT_DOUBLE_EQ(pbvs.rotation_gain().z(), 1.5); + EXPECT_DOUBLE_EQ(pbvs.vmax6().z(), 0.05); + EXPECT_DOUBLE_EQ(pbvs.amax6().rz(), 2.0); + EXPECT_DOUBLE_EQ(pbvs.twist_filter_alpha(), 1.0); + } EXPECT_TRUE(config.has_touch()); EXPECT_EQ(config.touch().motion_case(), cmvr::config::TouchScreenTaskTouchConfig::kSpeedL); EXPECT_TRUE(config.has_retract()); EXPECT_TRUE(config.retract().has_distance_m()); EXPECT_GT(config.retract().distance_m(), 0.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } +} + +TEST(TouchScreenTaskTest, MotorArmConfigurationsSupportMoveP) { + const auto project_root = findProjectRoot(); + ASSERT_FALSE(project_root.empty()); + for (const auto* file_name : {"arm.pb.txt", "arm_qp.pb.txt", "arm_mujoco.pb.txt", + "arm_mujoco_qp.pb.txt", "ethercat_dual_arm.pb.txt", + "arm_gen2_mujoco.pb.txt"}) { + SCOPED_TRACE(file_name); + cmvr::config::ArmRootConfig root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (project_root / "cmvr-es/config/devices/arm" / file_name).string(), &root)); + ASSERT_GT(root.arm().robot_arms_size(), 0); + for (const auto& arm : root.arm().robot_arms()) { + SCOPED_TRACE(arm.id()); + ASSERT_TRUE(arm.motion().has_joint_path()); + const auto& path = arm.motion().joint_path(); + ASSERT_NE(cmvr::JointPathPlannerFactory::create(path), nullptr); + EXPECT_TRUE(std::isfinite(path.minimum_distance_m())); + EXPECT_GE(path.minimum_distance_m(), 0.0); + const auto& joints = arm.motor().joint_names(); + cmvr::CollisionOptions options; + for (const auto& pair : path.collision_checker().ignored_pairs()) { + options.ignored_pairs.push_back({pair.first(), pair.second()}); + } + cmvr::CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + (project_root / path.collision_checker().urdf_path()).string(), + std::vector(joints.begin(), joints.end()), options, &error)) << error; + EXPECT_EQ(checker.dof(), arm.motor().dof()); + EXPECT_GT(checker.activePairCount(), 0); + } + } +} + +TEST(TouchScreenTaskTest, DisabledApproachPreservesExistingConfigBehavior) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + config.clear_approach(); + { + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } + auto* approach = config.mutable_approach(); + approach->set_enable(false); + approach->set_velocity(std::numeric_limits::quiet_NaN()); + approach->set_acceleration(-1.0); + approach->set_jerk(0.0); + approach->set_timeout_s(std::numeric_limits::infinity()); + approach->set_minimum_clearance_m(-1.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); +} + +TEST(TouchScreenTaskTest, EnabledApproachRequiresFinitePositiveMotionLimits) { + const auto valid_config = loadMujocoTouchConfig(findProjectRoot()); + ASSERT_TRUE(valid_config.approach().enable()); + using Approach = cmvr::config::TouchScreenTaskApproachConfig; + using Setter = void (Approach::*)(double); + const std::array, 4> setters{{ + {"velocity", &Approach::set_velocity}, + {"acceleration", &Approach::set_acceleration}, + {"jerk", &Approach::set_jerk}, + {"timeout_s", &Approach::set_timeout_s}, + }}; + for (const auto& [name, setter] : setters) { + for (const double value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(::testing::Message() << name << "=" << value); + auto config = valid_config; + (config.mutable_approach()->*setter)(value); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + } + for (const double clearance : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(::testing::Message() << "minimum_clearance_m=" << clearance); + auto config = valid_config; + config.mutable_approach()->set_minimum_clearance_m(clearance); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + { + auto config = valid_config; + config.mutable_approach()->set_minimum_clearance_m(0.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } + for (const double target_z : {0.0, valid_config.approach().minimum_clearance_m()}) { + SCOPED_TRACE(::testing::Message() << "target_z=" << target_z); + auto config = valid_config; + config.mutable_alignment()->mutable_target()->mutable_position_offset_g()->set_z(target_z); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); } } @@ -346,6 +808,61 @@ TEST(TouchScreenTaskTest, TouchSpeedLJerkIsOptionalAndMustBeFinitePositive) { } } +TEST(TouchScreenTaskTest, TactileRegionMustMatchSelectedFinger) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + for (const auto finger : {cmvr::config::TOUCH_SCREEN_FINGER_TYPE_PINKY, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_RING, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_MIDDLE, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_INDEX, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB}) { + for (const auto region : {cmvr::config::TOUCH_SCREEN_TACTILE_REGION_TIP, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_FINGER, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_PAD, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE}) { + SCOPED_TRACE(::testing::Message() << "finger=" << finger << ", region=" << region); + config.mutable_touch()->mutable_tactile()->set_finger(finger); + config.mutable_touch()->mutable_tactile()->set_region(region); + const bool valid = region != cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE || + finger == cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB; + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), valid + ? cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED + : cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + } +} + +TEST(TouchScreenTaskTest, InitializationRequiresUniqueCompleteFiniteJointPositions) { + const auto valid_config = loadMujocoTouchConfig(findProjectRoot()); + ASSERT_TRUE(valid_config.initialization().before_start()); + ASSERT_GT(valid_config.initialization().joint_positions_size(), 0); + const auto expect_invalid = [](const cmvr::config::TouchScreenTaskConfig& config) { + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + }; + for (const auto* invalid_case : {"empty", "missing_name", "empty_name", "missing_position", + "duplicate", "nan", "infinity"}) { + SCOPED_TRACE(invalid_case); + auto config = valid_config; + auto* initialization = config.mutable_initialization(); + const std::string name(invalid_case); + if (name == "empty") { + initialization->clear_joint_positions(); + } else if (name == "duplicate") { + const auto joint = initialization->joint_positions(0); + *initialization->add_joint_positions() = joint; + } else { + auto* joint = initialization->mutable_joint_positions(0); + if (name == "missing_name") joint->clear_joint_name(); + if (name == "empty_name") joint->set_joint_name(""); + if (name == "missing_position") joint->clear_rad(); + if (name == "nan") joint->set_rad(std::numeric_limits::quiet_NaN()); + if (name == "infinity") joint->set_rad(std::numeric_limits::infinity()); + } + expect_invalid(config); + } +} + TEST(TouchScreenTaskTest, CoordinateFrameProjectionUsesBgrAxisColors) { cv::Mat image = cv::Mat::zeros(240, 320, CV_8UC3); cmvr::device::Rs2Intrinsics intrinsics{}; @@ -388,12 +905,46 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { cmvr::ConfigHelper::setConfigRootFromFile( (project_root / "cmvr-es/config/cmvr_es.pb.txt").string()); + const auto touch_config = loadMujocoTouchConfig(project_root); + cmvr::config::DeviceManagerRootConfig runtime_devices; + ASSERT_TRUE(cmvr::ConfigHelper::loadConfigFile( + "manager/device_manager.pb.txt", runtime_devices)); + const auto& entries = runtime_devices.device_manager().devices(); + const auto arm_entry = std::find_if(entries.begin(), entries.end(), [](const auto& entry) { + return entry.id() == "mujoco_right_arm"; + }); + ASSERT_NE(arm_entry, entries.end()); + ASSERT_TRUE(arm_entry->enable()); + ASSERT_EQ(arm_entry->type(), cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM); + ASSERT_FALSE(arm_entry->config_file().empty()); + const auto arm_config_path = cmvr::ConfigHelper::resolveConfigFile(arm_entry->config_file()); + std::cout << "[TouchScreenTaskMujocoTest] selected arm config: " + << arm_config_path << std::endl; + cmvr::config::ArmRootConfig arm_root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(arm_config_path, &arm_root)); + const auto& arms = arm_root.arm().robot_arms(); + const auto arm_config = std::find_if(arms.begin(), arms.end(), [](const auto& config) { + return config.id() == "mujoco_right_arm"; + }); + ASSERT_NE(arm_config, arms.end()); + ASSERT_EQ(arm_config->motor().motor_system_id(), "right_arm_mujoco_motors"); + ASSERT_EQ(arm_config->motor().motor_group_ids_size(), 1); + ASSERT_EQ(arm_config->motor().motor_group_ids(0), "right_arm_mujoco_motors"); + const auto& kinematics = arm_config->kinematics(); + const auto& urdf_path = kinematics.has_pinocchio_qp_ik_solver() + ? kinematics.pinocchio_qp_ik_solver().urdf_path() + : kinematics.pinocchio_dls_ik_solver().urdf_path(); + ASSERT_EQ(urdf_path, "model/xiaoyan_description/dual_arm.urdf"); + if (touch_config.approach().enable()) { + ASSERT_TRUE(arm_config->motion().has_joint_path()) + << arm_config_path << " requires motion.joint_path for touch approach MoveP"; + } + cmvr::task::TaskManager::destroyInstance(); cmvr::device::DeviceManager::destroyInstance(); - // This test intentionally builds only the devices required by the - // MuJoCo Eye-to-Hand task. The task itself is still loaded from - // touch_screen_task_mujoco.pb.txt below. + // Build only the MuJoCo Eye-to-Hand devices while using the arm config + // selected by the runtime manager and the task's checked-in config. cmvr::config::DeviceManagerConfig device_manager_config; device_manager_config.set_name("touch_screen_eye_to_hand_mujoco_test"); device_manager_config.set_version("test"); @@ -416,7 +967,7 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { "devices/motor/mujoco_motors.pb.txt"); add_device("mujoco_right_arm", cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM, - "devices/arm/arm_mujoco.pb.txt"); + arm_entry->config_file().c_str()); add_device("mujoco_zero_touch_dexhand", cmvr::config::DeviceConfigEntry::DEVICE_TYPE_DEXHAND, "devices/dexhand/dexhand.pb.txt"); @@ -504,9 +1055,23 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { add_configured_pip(*external_mujoco_camera); add_configured_pip(*hand_mujoco_camera); + const char* autoclose_env = std::getenv("CMVR_TOUCH_TEST_AUTOCLOSE"); + const bool auto_close = autoclose_env && std::string(autoclose_env) == "1"; + const char* cancel_env = std::getenv("CMVR_TOUCH_TEST_CANCEL_APPROACH"); + const bool cancel_approach = cancel_env && std::string(cancel_env) == "1"; + const char* failure_env = std::getenv("CMVR_TOUCH_TEST_APPROACH_FAILURES"); + const bool check_approach_failures = failure_env && std::string(failure_env) == "1"; + struct Outcome { bool init_ok{false}; bool touch_ok{false}; + bool approach_seen{false}; + bool alignment_seen{false}; + bool alignment_before_approach{false}; + bool cancellation_ok{false}; + double cancellation_duration_s{0.0}; + bool rejection_ok{false}; + bool timeout_ok{false}; bool align_reached{false}; bool retracting_seen{false}; bool finished{false}; @@ -520,12 +1085,11 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::string error; } outcome; - // The viewer owns the lifetime of this test. Closing its window asks the - // worker to stop; a completed touch cycle must not close the viewer. + // Interactive runs keep the viewer open; automated runs opt in to closing + // after the scenario so gtest can report its assertions and exit. std::atomic stop_requested{false}; std::thread scenario([&] { try { - const auto touch_config = loadMujocoTouchConfig(project_root); if (touch_config.devices().arm_id() != "mujoco_right_arm" || touch_config.devices().camera_id() != "mujoco_hand_cam" || touch_config.devices().external_camera_id() != @@ -568,6 +1132,72 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::cout << "[TouchScreenTaskMujocoTest] touch target pixel: u=" << target_u << ", v=" << target_v << std::endl; + const auto max_joint_change = [](const std::vector& before, + const std::vector& after) { + if (before.empty() || before.size() != after.size()) { + throw std::runtime_error("invalid joint feedback in approach scenario"); + } + double change = 0.0; + for (std::size_t i = 0; i < before.size(); ++i) { + if (!std::isfinite(before[i]) || !std::isfinite(after[i])) { + throw std::runtime_error("nonfinite joint feedback in approach scenario"); + } + change = std::max(change, std::abs(after[i] - before[i])); + } + return change; + }; + + if (cancel_approach) { + if (!touch_config.approach().enable() || + !task->touch(target_u, target_v)) { + throw std::runtime_error("failed to start approach cancellation scenario"); + } + const auto cancel_deadline = std::chrono::steady_clock::now() + + std::chrono::duration(touch_config.approach().timeout_s() + 2.0); + const auto approach_start_joints = arm->getJointState().position; + bool approach_in_progress = false; + while (!stop_requested.load(std::memory_order_acquire) && + task->isBusy() && std::chrono::steady_clock::now() < cancel_deadline) { + if (task->phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING && + arm->busy()) { + const auto joints = arm->getJointState(); + const bool moving = max_joint_change(approach_start_joints, joints.position) > 1e-4 || + std::any_of(joints.velocity.begin(), joints.velocity.end(), + [](double velocity) { return std::abs(velocity) > 0.01; }); + if (moving && task->phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING) { + approach_in_progress = true; + break; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + const auto stop_start = std::chrono::steady_clock::now(); + task->stop(); + outcome.cancellation_duration_s = std::chrono::duration( + std::chrono::steady_clock::now() - stop_start).count(); + if (!approach_in_progress) { + throw std::runtime_error("never observed active MoveP before cancellation"); + } + // Keep periodic stepping active: neither the stopped worker nor + // a later step may resume commands or advance the stopped run. + const auto idle_deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(100); + do { + const auto status = task->lastStatus(); + if (task->isBusy() || arm->busy() || + task->phase() != cmvr::task::TouchScreenTask::Phase::IDLE || + (status != cmvr::task::TouchScreenTask::Status::STOPPED && + status != cmvr::task::TouchScreenTask::Status::IDLE)) { + throw std::runtime_error("approach cancellation left active motion or task state"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < idle_deadline); + outcome.cancellation_ok = true; + std::cout << "[TouchScreenTaskMujocoTest] approach cancelled in " + << outcome.cancellation_duration_s << " s; restarting touch" + << std::endl; + } + const bool touch_started = task->touch(target_u, target_v); if (!touch_started) { throw std::runtime_error( @@ -599,6 +1229,13 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::sqrt(speedl.vx * speedl.vx + speedl.vy * speedl.vy + speedl.vz * speedl.vz)); const auto phase = task->phase(); + if (phase == cmvr::task::TouchScreenTask::Phase::APPROACHING) { + outcome.approach_seen = true; + } + if (phase == cmvr::task::TouchScreenTask::Phase::ALIGNING) { + outcome.alignment_seen = true; + outcome.alignment_before_approach |= !outcome.approach_seen; + } if (task->lastStatus() == cmvr::task::TouchScreenTask::Status::ALIGN_REACHED || phase == cmvr::task::TouchScreenTask::Phase::TOUCHING || @@ -623,9 +1260,6 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { << cmvr::task::TouchScreenTask::statusToString( task->lastStatus()) << ", active_tag=" << task->lastActiveTagId() - << ", tcp_pose=" - << cmvr::perception::TagRelativeTcpPose::statusToString( - task->tcpPoseTracker().lastStatus()) << ", pressure=" << task->lastTouchPressureSum() << std::endl; } @@ -642,22 +1276,92 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { outcome.finished = task->isFinished(); outcome.final_phase = task->phase(); outcome.final_status = task->lastStatus(); + outcome.max_pressure = std::max( + outcome.max_pressure, task->lastTouchPressureSum()); + + if (check_approach_failures) { + task->stop(); + task_manager.stopRunTask(); + const auto stays_stationary = [&](const std::vector& positions) { + const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(100); + do { + if (arm->busy() || max_joint_change(positions, arm->getJointState().position) > 1e-4) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < until); + return true; + }; + const auto before_rejection = arm->getJointState().position; + cmvr::device::MotionOptions reject_options; + reject_options.velocity = touch_config.approach().velocity(); + reject_options.acceleration = touch_config.approach().acceleration(); + reject_options.jerk = touch_config.approach().jerk(); + bool predicate_called = false; + reject_options.is_tcp_pose_valid = [&](const cmvr::device::CartesianPose&) { + predicate_called = true; + return false; + }; + const auto rejected = arm->moveP(arm->getTcpPose(), reject_options); + outcome.rejection_ok = !rejected.ok() && predicate_called && stays_stationary(before_rejection); + if (!outcome.rejection_ok) { + throw std::runtime_error("MoveP did not reject the TCP constraint without motion"); + } + + auto timeout_config = touch_config; + timeout_config.mutable_approach()->set_timeout_s(0.001); + timeout_config.mutable_initialization()->set_before_start(false); + timeout_config.mutable_initialization()->set_after_finish(true); + timeout_config.mutable_initialization()->set_after_failure(false); + // A different return target makes an unintended automatic MoveJ observable. + auto* return_joint = timeout_config.mutable_initialization()->mutable_joint_positions(0); + return_joint->set_rad(return_joint->rad() + 0.05); + cmvr::task::TouchScreenTask timeout_task(timeout_config); + auto dexhand = device_manager.getDevice( + touch_config.devices().dexhand_id()); + if (!timeout_task.init(arm, dexhand, hand_camera, external_camera) || + !timeout_task.touch(target_u, target_v)) { + throw std::runtime_error("failed to start approach timeout scenario"); + } + const auto before_timeout = arm->getJointState().position; + const auto timeout_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + bool timeout_approach_seen = false; + bool timeout_alignment_seen = false; + while (!stop_requested.load(std::memory_order_acquire) && timeout_task.isBusy() && + std::chrono::steady_clock::now() < timeout_deadline) { + const bool step_ok = timeout_task.step(0.001); + timeout_approach_seen |= timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING; + timeout_alignment_seen |= timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::ALIGNING; + if (!step_ok) break; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + outcome.timeout_ok = timeout_approach_seen && !timeout_alignment_seen && + timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::FAILED && + timeout_task.lastStatus() == cmvr::task::TouchScreenTask::Status::APPROACH_TIMEOUT && + stays_stationary(before_timeout); + timeout_task.stop(); + if (!outcome.timeout_ok) { + throw std::runtime_error("approach timeout advanced alignment or moved after failure"); + } + std::cout << "[TouchScreenTaskMujocoTest] constraint rejection and timeout passed" << std::endl; + } + std::cout << "[TouchScreenTaskMujocoTest] touch finished once, phase=" << cmvr::task::TouchScreenTask::phaseToString( outcome.final_phase) - << "; viewer remains running" << std::endl; + << (auto_close ? "; closing viewer" : "; viewer remains running") + << std::endl; - // Keep the viewer and its camera frames alive after the task has - // run once. The main thread sets stop_requested when the window - // is closed. - while (!stop_requested.load(std::memory_order_acquire)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + if (auto_close) { + viewer.requestStop(); + } else { + while (!stop_requested.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } } task->stop(); task_manager.stopRunTask(); - std::cout << "[TouchScreenTaskMujocoTest] viewer is still running; " - "close the MuJoCo window to finish gtest." << std::endl; } catch (const std::exception& error) { try { cmvr::task::TaskManager::getInstance().stopRunTask(); @@ -665,9 +1369,11 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { } outcome.error = error.what(); stop_requested.store(true, std::memory_order_release); + if (auto_close) viewer.requestStop(); std::cerr << "[TouchScreenTaskMujocoTest] scenario error: " << outcome.error - << "; viewer remains open, close it manually to finish gtest." + << (auto_close ? "; closing viewer" + : "; viewer remains open, close it manually to finish gtest.") << std::endl; } }); @@ -684,8 +1390,31 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { EXPECT_TRUE(outcome.error.empty()) << outcome.error; EXPECT_TRUE(outcome.init_ok); EXPECT_TRUE(outcome.touch_ok); + if (touch_config.approach().enable()) { + EXPECT_TRUE(outcome.approach_seen); + EXPECT_TRUE(outcome.alignment_seen); + EXPECT_FALSE(outcome.alignment_before_approach); + } + if (cancel_approach) { + EXPECT_TRUE(outcome.cancellation_ok); + EXPECT_LT(outcome.cancellation_duration_s, 1.0); + } + if (check_approach_failures) { + EXPECT_TRUE(outcome.rejection_ok); + EXPECT_TRUE(outcome.timeout_ok); + } EXPECT_TRUE(outcome.align_reached); EXPECT_GT(outcome.speedl_command_norm, 0.005); + if (!touch_config.alignment().pause_when_reached()) { + // ZeroSimTouchDexHand always reports zero force. This scenario must + // reach the forward-distance limit, retract, and report no contact. + EXPECT_DOUBLE_EQ(outcome.max_pressure, 0.0); + EXPECT_TRUE(outcome.retracting_seen); + EXPECT_FALSE(outcome.finished); + EXPECT_EQ(outcome.final_phase, cmvr::task::TouchScreenTask::Phase::FAILED); + EXPECT_EQ(outcome.final_status, + cmvr::task::TouchScreenTask::Status::TOUCH_FORWARD_TIMEOUT); + } } TEST(TouchScreenTaskTest, DISABLED_RunTouchOnceInMujoco) { diff --git a/data/ik/plot_joint_traj.py b/data/ik/plot_joint_traj.py deleted file mode 100644 index 01c4a884..00000000 --- a/data/ik/plot_joint_traj.py +++ /dev/null @@ -1,59 +0,0 @@ -# pip install toppra numpy scipy pandas matplotlib -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import toppra as ta -import toppra.algorithm as algo -import toppra.constraint as constraint -import toppra.interpolator as interp - -# === 1) 读取 CSV(只取 q1..q7)=== -CSV_PATH = "/home/lgv/cmvr/cmvr-es/data/ik_psi_sweep.csv" # -joint_cols = ["q1","q2","q3","q4","q5","q6","q7"] -df = pd.read_csv(CSV_PATH) -assert all(c in df.columns for c in joint_cols), "CSV 缺少关节列 q1..q7" -waypoints = df[joint_cols].to_numpy() -N, dof = waypoints.shape -assert N >= 2, "至少需要两行关节路点" - -# === 2) 构造样条路径(路径参数 s∈[0,1])=== -s_grid = np.linspace(0, 1, N) -path = interp.SplineInterpolator(s_grid, waypoints) - -# === 3) 约束(示例值:请改成你的真实上限)=== -vmax = np.array([1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5]) # rad/s -amax = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) # rad/s^2 -vlim = np.vstack([-vmax, vmax]).T -alim = np.vstack([-amax, amax]).T -pc_vel = constraint.JointVelocityConstraint(vlim) -pc_acc = constraint.JointAccelerationConstraint(alim) - -# === 4) toppra 时间最优轨迹(起止速度=0)=== -topp = algo.TOPPRA([pc_vel, pc_acc], path, solver_wrapper="seidel") -traj = topp.compute_trajectory(0.0, 0.0) -T = traj.get_duration() -print(f"Total duration: {T:.4f} s") - -# === 5) 采样并绘图 === -ts = np.linspace(0, T, 300) -q = traj.eval(ts) # (300,7) -qd = traj.evald(ts) -qdd = traj.evaldd(ts) - -# 位置 -plt.figure() -for i in range(dof): - plt.plot(ts, q[:, i], label=f"q{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Position (rad)"); plt.title("Joint Positions"); plt.legend(); plt.tight_layout(); plt.show() - -# 速度 -plt.figure() -for i in range(dof): - plt.plot(ts, qd[:, i], label=f"qd{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Velocity (rad/s)"); plt.title("Joint Velocities"); plt.legend(); plt.tight_layout(); plt.show() - -# 加速度 -plt.figure() -for i in range(dof): - plt.plot(ts, qdd[:, i], label=f"qdd{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Acceleration (rad/s²)"); plt.title("Joint Accelerations"); plt.legend(); plt.tight_layout(); plt.show() diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp deleted file mode 100644 index 84a8f2ee..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp +++ /dev/null @@ -1,168 +0,0 @@ -#ifndef TOPPRA_ALGORITHM_HPP -#define TOPPRA_ALGORITHM_HPP - -#include -#include -#include -#include -#include -#include - -namespace toppra { - -/// Return code for Path Parametrization algorithm. -enum class ReturnCode { - - /// Success - OK = 0, - - /// Unknown error - ERR_UNKNOWN = 1, - - /// Fail during computing controllable sets. Problem might be infeasible. - ERR_FAIL_CONTROLLABLE = 2, - - /// Fail during forward pass. Numerical error occured. - ERR_FAIL_FORWARD_PASS = 3, - - /// Problem is not initialized - ERR_UNINITIALIZED = 4, - - /// Fail to ocmpute feasible sets. - ERR_FAIL_FEASIBLE = 5, -}; - -struct ParametrizationData { - /// \brief Grid-points used for solving the discretized problem. - /// The number of points must equal m_N + 1. - Vector gridpoints; - - /// Output parametrization (squared path velocity) - Vector parametrization; - - Matrix controllable_sets; - Matrix feasible_sets; - - /// Return code of the algorithm. - ReturnCode ret_code = ReturnCode::ERR_UNINITIALIZED; -}; - -/** \brief Base class for time parametrization algorithms. - * - */ -class PathParametrizationAlgorithm { - public: - /** Construct the problem instance. - * - * \param constraints List of constraints. - * \param path The geometric path. - * - */ - PathParametrizationAlgorithm(LinearConstraintPtrs constraints, - const GeometricPathPtr &path); - - /** \brief Set the level of discretization used by the solver. - * - * If is zero, will attempt to detect automatically the most - * suitable grid. - * - * TODO: Automatic gridpoint selection is not implemented in the CPP - * API. - */ - void setN(int N) { m_N = N; m_initialized = false; }; - - /** \brief Set the gridpoints (points with the path intervals) - * - * If not set manually, then N equally distributed points is used. - */ - void setGridpoints(const Vector& gridpoints); - - /** \brief Set the LP/QP solver - * - * Default to \ref solver::qpOASESWrapper - */ - void solver(SolverPtr solver) { m_solver.swap(solver); }; - - /** \brief Get output or result of algorithm. - */ - const ParametrizationData& getParameterizationData() const { return m_data; }; - - /** Compute the time parametrization of the given path. - * - * \param vel_start - * \param vel_end - * \return Return code. When not ReturnCode::OK, - * check PathParametrizationAlgorithm::getErrorMessage - */ - virtual ReturnCode computePathParametrization(value_type vel_start = 0, - value_type vel_end = 0); - - /** Compute the sets of feasible squared velocities. - */ - ReturnCode computeFeasibleSets(); - - /** Set initial bounds on \f$ \dot{s}^2. - * This is helpfull when the solver encounters numerical issues. - */ - void setInitialXBounds (const Bound& xbound) - { - m_initXBound = xbound; - } - - /** Get the error message when PathParametrizationAlgorithm::computePathParametrization - * failed. - */ - std::string getErrorMessage() const { - return m_errorStream.str(); - } - - virtual ~PathParametrizationAlgorithm() {} - - protected: - /** \brief Select solver and gridpoints to use. - * - * This method implements a simple way to select gridpoints. - */ - virtual void initialize(); - - /** \brief Compute the forward pass. - * - * Derived class should provide a suitable forward pass function, - * depending on the desired objective. - */ - virtual ReturnCode computeForwardPass(value_type vel_start) = 0; - - /** Compute the sets of controllable squared path velocities. - */ - ReturnCode computeControllableSets(const Bound &vel_ends); - - /** To be implemented in child method. */ - LinearConstraintPtrs m_constraints; - GeometricPathPtr m_path; - SolverPtr m_solver; - - std::stringstream m_errorStream; - - /// Struct containing algorithm output. - ParametrizationData m_data; - - /// \brief Number of segments in the discretized problems. - /// See m_gridpoints for more information. - int m_N = 100; - - int m_initialized = false; - - /** Set initial bounds on \f$ \dot{s}^2. - * \sa setInitialXBounds - * \todo The hard-coded bound below avoids numerical issues in LP / QP solvers - * when \f$ x \f$ becomes too big. This issue should be addressed in the - * solver wrapper themselfves as numerical behaviors is proper to each - * individual solver. - * See https://github.com/hungpham2511/toppra/issues/156 - */ - Bound m_initXBound = {0, 100}; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp deleted file mode 100644 index 3956e87e..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef TOPPRA_ALGORITHM_TOPPRA_HPP -#define TOPPRA_ALGORITHM_TOPPRA_HPP - -#include -#include -#include -#include "toppra/toppra.hpp" - -namespace toppra { -namespace algorithm { -class TOPPRA : public PathParametrizationAlgorithm { - public: - TOPPRA(LinearConstraintPtrs constraints, const GeometricPathPtr &path); - - protected: - ReturnCode computeForwardPass(value_type vel_start); -}; -} // namespace algorithm -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp deleted file mode 100644 index 97e0a666..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp +++ /dev/null @@ -1,174 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_HPP -#define TOPPRA_CONSTRAINT_HPP - -#include -#include - -namespace toppra { -/** Enum to mark different Discretization Scheme for LinearConstraint. - * In general, the difference in speed is not too large. Should use - * \ref Interpolation if possible. - * */ -enum DiscretizationType { - Collocation, ///< smaller problem size, but lower accuracy. - Interpolation, ///< larger problem size, but higher accuracy. -}; - -/** \brief Abstract interface for constraints used in TOPPRA. - * - * This class of constraint is also known as Second-order Constraint. - * - * A Canonical Linear Constraint has the following form: - * \f{eqnarray} - * \mathbf a_i u + \mathbf b_i x + \mathbf c_i &= v \\ - * \mathbf F_i v & \leq \mathbf g_i \\ - * x^b_{i, 0} \leq x & \leq x^b_{i, 1} \\ - * u^b_{i, 0} \leq u & \leq u^b_{i, 1} - * \f} - * - * Here \f$u\f$ and \f$x\f$ represent the path acceleration and path velocity - * square. \f$v$\f is an auxilliary variable that represents either the robot - * joint/taskspace velocity, acceleration or torque, or just the squared path - * velocity term only. - * - * Alternatively, if \f$ \mathbf F_i \f$ is constant for all values - * of \f$i\f$, then we can consider the simpler constraint: - * \f[ - * \mathbf{F} v \leq \mathbf g - * \f] - * - * In this case, the returned value of \f$F\f$ by - * LinearConstraint::computeParams has shape (k, m) instead of (N, k, m), - * \f$ g \f$ (k) instead of (N, k) and the class attribute - * LinearConstraint::constantF will be \c true. - * - * \note Derived classes should at least implement the method - * LinearConstraint::computeParams_impl. - * - * \sa JointAccelerationConstraint, JointVelocityConstraint, - * CanonicalLinearSecondOrderConstraint - * - * */ -class LinearConstraint { - public: - DiscretizationType discretizationType () const - { - return m_discretizationType; - } - - void discretizationType (DiscretizationType type); - - /** Tells whether \f$ F, g \f$ matrices are the same over all the grid points. - * In this case, LinearConstraint::computeParams F and g parameters should - * only be of size 1. - * */ - bool constantF () const - { - return m_constantF; - } - - /// Dimension of \f$g\f$. - Eigen::Index nbConstraints () const - { - return m_k; - } - - /// Dimension of \f$a, b, c, v\f$. - Eigen::Index nbVariables () const - { - return m_m; - } - - bool hasLinearInequalities () const - { - return nbConstraints() > 0; - } - - /** Whether this constraint has bounds on \f$u\f$. - * */ - bool hasUbounds () const - { - return m_hasUbounds; - } - - /** Whether this constraint has bounds on \f$x\f$. - * */ - bool hasXbounds () const - { - return m_hasXbounds; - } - - /** - * \param N number of gripoints (i.e. the number of intervals + 1) - * */ - void allocateParams (std::size_t N, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds ubound, Bounds& xbound); - - /** Compute numerical coefficients of the given constraint. - * - * \param[in] path The geometric path. - * \param[in] gridpoints Vector of size N+1. Gridpoint use for discretizing path. - * - * \param[out] a N+1 Vector of size m. - * \param[out] b N+1 Vector of size m. - * \param[out] c N+1 Vector of size m. - * \param[out] F N+1 Matrix of shape (k, m). If LinearConstraint::constantF - * is \c true, there is only one such Matrix. - * \param[out] g N+1 Vector of size m. - * \param[out] ubound Shape (N + 1, 2). See notes. - * \param[out] xbound Shape (N + 1, 2). See notes. - * - * \note the output must be allocated to correct sizes prior to calling this - * function. - * - * \todo check constness - * - * */ - void computeParams(const GeometricPath& path, const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - virtual std::ostream& print(std::ostream& os) const; - - virtual ~LinearConstraint () {} - - protected: - /** - * \param k number of inequality constraints. - * \param m number of internal variable (i.e. dimention of \f$v\f$). - * \param constantF whether \f$F\f$ and \f$g\f$ are constant. - * \param uBound whether \f$u\f$ is bounded. - * \param xBound whether \f$x\f$ is bounded. - * */ - LinearConstraint(Eigen::Index k, Eigen::Index m, bool constantF, - bool uBound, bool xBound) - : m_discretizationType (Interpolation) - , m_k (k), m_m (m) - , m_constantF (constantF) - , m_hasUbounds (uBound) - , m_hasXbounds (xBound) - {} - - virtual void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound) = 0; - - Eigen::Index m_k, m_m; - DiscretizationType m_discretizationType; - bool m_constantF, m_hasUbounds, m_hasXbounds; -}; // class LinearConstraint - -/// \brief write a LinearConstraint to an output stream -inline std::ostream& operator<< (std::ostream& os, const LinearConstraint& lc) -{ - return lc.print(os); -} - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp deleted file mode 100644 index bb3d8515..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_HPP -#define TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_HPP - -#include - -namespace toppra { -namespace constraint { - -/** -\brief A cartesian velocity constraint class. - -Given a path \f$ p(s) \f$, this class constraints the norm -\f$||v||_S^2 = v^T S v \leq limit \f$ of the velocity \f$v\f$ of a frame. -As \f$ v = J(p(s)) p'(s) \dot{s} \f$, it fits into a LinearConstraint as follows. - -\f{eqnarray} - p'(s)^T J(q)^T S J(q) p'(s) \dot{s}^2 &= w \\ - w & \leq \mathbf g_i \\ -\f} - -This class implements the case of constant velocity limits but can be derived to -achieve varying velocity limits. E.g. -\code -class CartesianVelocityVarying : public CartesianVelocityNorm { -public: - CartesianVelocityVarying(...) : CartesianVelocityNorm () {} -protected: - void computeVelocityLimit(value_type time) - { - // Eventually, if one of the two is constant, it can be set in the constructor. - m_limit = ...; - m_S = ...; - } -}; -\endcode -*/ -class CartesianVelocityNorm : public LinearConstraint { - public: - virtual std::ostream& print(std::ostream& os) const; - - protected: - /// Constructor for constant velocity limit. - CartesianVelocityNorm (const Matrix& S, const double& limit) - : LinearConstraint (1, 1, true, false, false) - , m_limit (limit) - , m_S (S) - { - check(); - } - - /// Constructor for varying velocity limit. - /// \note Attributes \ref m_S and \ref m_limit **must** be computed in - /// \ref computeVelocityLimit - CartesianVelocityNorm () - : LinearConstraint (1, 1, false, false, false) - , m_limit (1.) - , m_S (6,6) - { - check(); - } - - /// Pure abstract method to compute the velocity from - /// \param q the current configuration - /// \param qdot the current velocity - /// \retval v the 6D frame velocity - virtual void computeVelocity (const Vector& q, const Vector& qdot, - Vector& v) = 0; - - /** - \brief Computes the velocity limit at time \c time. - - The result must be stored into attribute - CartesianVelocityNorm::m_limit - */ - virtual void computeVelocityLimit(value_type time) { (void)time; } - - /// The velocity limit - value_type m_limit; - /// The selection matrix - Matrix m_S; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); -}; // class CartesianVelocityNorm -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp deleted file mode 100644 index 23515af2..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_PINOCCIO_HPP -#define TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_PINOCCIO_HPP - -#include -#include - -#include -#include - -#include - -namespace toppra { -namespace constraint { -namespace cartesianVelocityNorm { - -/** Implementation of CartesianVelocityNorm using pinocchio function. - * \extends CartesianVelocityNorm - * */ -template -class Pinocchio; - -template -class Pinocchio : public CartesianVelocityNorm { - public: - typedef _Model Model; - typedef typename Model::Data Data; - - std::ostream& print(std::ostream& os) const - { - return CartesianVelocityNorm::print(os << "Pinocchio - "); - } - - void computeVelocity (const Vector& q, const Vector& qdot, Vector& v) - { - pinocchio::forwardKinematics(m_model, m_data, q, qdot); - v = pinocchio::getFrameVelocity(m_model, m_data, m_frame_id, m_reference_frame).toVector(); - } - - /// Constructor for constant velocity limit. - Pinocchio (const Model& model, const Matrix& S, const double& limit, - pinocchio::FrameIndex frame, - pinocchio::ReferenceFrame ref_frame = pinocchio::LOCAL_WORLD_ALIGNED) - : CartesianVelocityNorm (S, limit) - , m_model (model) - , m_data (model) - , m_frame_id (frame) - , m_reference_frame (ref_frame) - { - } - - /// Move-assignment operator - Pinocchio (Pinocchio&& other) - : CartesianVelocityNorm(other) - , m_model (other.m_model) - , m_data (std::move(other.m_data)) - , m_frame_id (m_frame_id) - , m_reference_frame (m_reference_frame) - {} - - const Model& model() const { return m_model; } - - protected: - /// Constructor for varying velocity limit. - Pinocchio (const Model& model, - pinocchio::FrameIndex frame, - pinocchio::ReferenceFrame ref_frame = pinocchio::LOCAL_WORLD_ALIGNED) - : CartesianVelocityNorm () - , m_model (model) - , m_data (model) - , m_frame_id (frame) - , m_reference_frame (ref_frame) - {} - - - private: - const Model& m_model; - Data m_data; - pinocchio::FrameIndex m_frame_id; - pinocchio::ReferenceFrame m_reference_frame; -}; // class Pinocchio - -} // namespace cartesianVelocityNorm -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp deleted file mode 100644 index ce36dc81..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_JOINT_TORQUE_HPP -#define TOPPRA_CONSTRAINT_JOINT_TORQUE_HPP - -#include - -namespace toppra { -namespace constraint { - -/** Base class for joint torque constraints. - * - * A joint torque constraint is given by - * \f[ - * A(q) \ddot q + \dot q^\top B(q) \dot q + C(q) + D( \dot q )= \tau - * \f] - * - * where w is a vector that satisfies the polyhedral constraint: - * \f[ F \tau \leq g \f] - * - * Notice that \f$ inverseDynamics(q, qd, qdd) = \tau\f$ and that - * \f$ F, g \f$ are independant of the GeometricPath. - * - * To evaluate the constraint on a geometric path `p(s)`, multiple - * calls to \ref computeInverseDynamics are made. Specifically one - * can derive the second-order equation as follows - * - * \f{eqnarray} - * A(q) p'(s) \ddot s &+ [A(q) p''(s) + p'(s)^\top B(q) p'(s)] \dot s^2 &+ C(q) + D( \dot q ) &= \tau \\ - * a(s) \ddot s &+ b(s) \dot s^2 &+ c(s) &= \tau - * \f} - * - * */ -class JointTorque : public LinearConstraint { - public: - virtual ~JointTorque () {} - - virtual std::ostream& print(std::ostream& os) const; - - /** Computes the joint torques from - * \param q robot configuration - * \param v robot velocity - * \param a robot acceleration - * \param[out] joint torques - * */ - virtual void computeInverseDynamics (const Vector& q, const Vector& v, const Vector& a, - Vector& tau) = 0; - - const Vector& lowerBounds () const - { return m_lower; } - - void lowerBounds (const Vector& lb) - { - assert(lb.size() == m_lower.size()); - m_lower = lb; - } - - const Vector& upperBounds () const - { return m_upper; } - - void upperBounds (const Vector& ub) - { - assert(ub.size() == m_upper.size()); - m_upper = ub; - } - - const Vector& frictionCoeffs () const - { return m_frictionCoeffs; } - - void frictionCoeffs (const Vector& fc) - { - assert(fc.size() == m_frictionCoeffs.size()); - m_frictionCoeffs = fc; - } - - protected: - /** - * \param lowerTlimit lower torque limit - * \param upperTlimit upper torque limit - * \param frictionCoeffs dry friction coefficients of each joint. - * size 0 when not considering friction. - * */ - JointTorque (const Vector& lowerTlimit, const Vector& upperTlimit, - const Vector& frictionCoeffs) - : LinearConstraint (2*lowerTlimit.size(), lowerTlimit.size(), true, false, false) - , m_lower (lowerTlimit) - , m_upper (upperTlimit) - , m_frictionCoeffs (frictionCoeffs) - { - check(); - } - - /// Move-assignment constructor - JointTorque (JointTorque&& other) - : LinearConstraint (other) - , m_lower(std::move(other.m_lower)) - , m_upper(std::move(other.m_upper)) - , m_frictionCoeffs(std::move(other.m_frictionCoeffs)) - {} - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - Vector m_lower, m_upper, m_frictionCoeffs; -}; // class JointTorque -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp deleted file mode 100644 index 903abba1..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP -#define TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP - -#include -#include -#include -#include - -#include - -namespace toppra { -namespace constraint { -namespace jointTorque { - -/** Implementation of JointTorque using pinocchio::rnea function. - * \extends JointTorque - * */ -template -class Pinocchio; - -template -class Pinocchio : public JointTorque { - public: - typedef _Model Model; - typedef typename Model::Data Data; - - std::ostream& print(std::ostream& os) const - { - return JointTorque::print(os << "Pinocchio - "); - } - - void computeInverseDynamics (const Vector& q, const Vector& v, const Vector& a, - Vector& tau) - { - tau = pinocchio::rnea(m_model, m_data, q, v, a); - } - - Pinocchio (const Model& model, const Vector& frictionCoeffs = Vector()) - : JointTorque (-model.effortLimit, model.effortLimit, frictionCoeffs) - , m_model (model) - , m_data (model) - { - } - - /// Move-assignment operator - Pinocchio (Pinocchio&& other) - : JointTorque(other) - , m_storage (std::move(other.m_storage)) - , m_model (other.m_model) - , m_data (std::move(other.m_data)) - {} - - Pinocchio (const std::string& urdfFilename, const Vector& friction = Vector()) - : Pinocchio (makeModel(urdfFilename), friction) {} - - const Model& model() const { return m_model; } - - private: - /// Build a pinocchio::Model - /// \param urdfFilename path to a URDF file. - static Model* makeModel (const std::string& urdfFilename) - { - Model* model (new Model); - pinocchio::urdf::buildModel(urdfFilename, *model); - return model; - } - - /// Constructor that takes ownership of the model - Pinocchio (Model* model, const Vector& friction) - : JointTorque (-model->effortLimit, model->effortLimit, friction) - , m_storage (model) - , m_model (*model) - , m_data (m_model) - { - } - - /// Store the pinocchio::Model object, in case this object owns it. - std::unique_ptr m_storage; - const Model& m_model; - Data m_data; -}; // class Pinocchio - -} // namespace jointTorque -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp deleted file mode 100644 index 2da8fda3..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_LINEAR_JOINT_ACCELERATION_HPP -#define TOPPRA_CONSTRAINT_LINEAR_JOINT_ACCELERATION_HPP - -#include - -namespace toppra { -namespace constraint { - -/// A Joint Acceleration Constraint class. -class LinearJointAcceleration : public LinearConstraint { - public: - LinearJointAcceleration (const Vector& lowerAlimit, const Vector& upperAlimit) - : LinearConstraint (lowerAlimit.size() * 2, lowerAlimit.size(), true, false, false) - , m_lower (lowerAlimit) - , m_upper (upperAlimit) - { - check(); - } - - virtual std::ostream& print(std::ostream& os) const; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - Vector m_lower, m_upper; -}; // class LinearJointAcceleration -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp deleted file mode 100644 index a269c94b..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_LINEAR_JOINT_VELOCITY_HPP -#define TOPPRA_CONSTRAINT_LINEAR_JOINT_VELOCITY_HPP - -#include - -namespace toppra { -namespace constraint { - -/** -\brief A Joint Velocity Constraint class. - -This class implements the case of constant velocity limits but can be derived to -achieve varying velocity limits. E.g. -\code -class LinearJointVelocityVarying : public LinearJointVelocity { -public: - LinearJointVelocityVarying(...) : LinearJointVelocity (nDof) {} -protected: - void computeVelocityLimits(value_type time) - { - m_lower = ...; - m_upper = ...; - } -}; -\endcode -*/ -class LinearJointVelocity : public LinearConstraint { - public: - LinearJointVelocity (const Vector& lowerVlimit, const Vector& upperVlimit) - : LinearConstraint (0, 0, true, false, true) - , m_lower (lowerVlimit) - , m_upper (upperVlimit) - , m_maxsd (1e8) - { - check(); - } - - /** Set the maximum allowed value of \f$\dot s\f$. - * \param maxsd should be strictly positive. - * */ - void maxSDot (value_type maxsd) - { - assert(maxsd > 0); - m_maxsd = maxsd; - } - - virtual std::ostream& print(std::ostream& os) const; - - protected: - LinearJointVelocity (const int nDof) - : LinearConstraint (0, 0, true, false, true) - , m_lower (nDof) - , m_upper (nDof) - , m_maxsd (1e8) - { - check(); - } - - /** - \brief Computes the velocity limit at time \c time. - - The result must be stored into attributes - LinearJointVelocity::m_lower and LinearJointVelocity::m_upper. - */ - virtual void computeVelocityLimits(value_type time) { (void)time; } - - /// The lower velocity limits - Vector m_lower; - /// The upper velocity limits - Vector m_upper; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - value_type m_maxsd; -}; // class LinearJointVelocity -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp deleted file mode 100644 index cf498d88..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp +++ /dev/null @@ -1,43 +0,0 @@ - -#ifndef TOPPRA_EXPORT_H -#define TOPPRA_EXPORT_H - -#ifdef TOPPRA_STATIC_DEFINE -# define TOPPRA_EXPORT -# define TOPPRA_NO_EXPORT -#else -# ifndef TOPPRA_EXPORT -# ifdef toppra_EXPORTS - /* We are building this library */ -# define TOPPRA_EXPORT __attribute__((visibility("default"))) -# else - /* We are using this library */ -# define TOPPRA_EXPORT __attribute__((visibility("default"))) -# endif -# endif - -# ifndef TOPPRA_NO_EXPORT -# define TOPPRA_NO_EXPORT __attribute__((visibility("hidden"))) -# endif -#endif - -#ifndef TOPPRA_DEPRECATED -# define TOPPRA_DEPRECATED __attribute__ ((__deprecated__)) -#endif - -#ifndef TOPPRA_DEPRECATED_EXPORT -# define TOPPRA_DEPRECATED_EXPORT TOPPRA_EXPORT TOPPRA_DEPRECATED -#endif - -#ifndef TOPPRA_DEPRECATED_NO_EXPORT -# define TOPPRA_DEPRECATED_NO_EXPORT TOPPRA_NO_EXPORT TOPPRA_DEPRECATED -#endif - -/* NOLINTNEXTLINE(readability-avoid-unconditional-preprocessor-if) */ -#if 0 /* DEFINE_NO_DEPRECATED */ -# ifndef TOPPRA_NO_DEPRECATED -# define TOPPRA_NO_DEPRECATED -# endif -#endif - -#endif /* TOPPRA_EXPORT_H */ diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp deleted file mode 100644 index cd6a49d6..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef TOPPRA_GEOMETRIC_PATH_HPP -#define TOPPRA_GEOMETRIC_PATH_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace toppra { - - -/** - * \brief Abstract interface for geometric paths. - */ -class GeometricPath { -public: - - GeometricPath() = default; - - /** - * Constructor of GeometricPath on vector spaces. - */ - GeometricPath(int nDof) : m_configSize(nDof), m_dof (nDof) {} - - /** - * Constructor of GeometricPath on non-vector spaces. - */ - GeometricPath(int configSize, int nDof) : m_configSize(configSize), m_dof (nDof) {} - - /** - * \brief Evaluate the path at given position. - */ - virtual Vector eval_single(value_type, int order = 0) const = 0; - - /** - * \brief Evaluate the path at given positions (vector). - * - * Default implementation: Evaluation each point one-by-one. - */ - virtual Vectors eval(const Vector &positions, int order = 0) const; - - /** - \brief Generate gridpoints that sufficiently cover the given path. - - This function operates in multiple passes through the geometric - path from the start to the end point. In each pass, for each - segment, the maximum interpolation error is estimated using the - following equation: - - err_{est} = 0.5 * \mathrm{max}(\mathrm{abs}(p'' * d_{segment} ^ 2)) - - Here `p''` is the second derivative of the path and d_segment is - the length of the segment. If the estimated error `err_{test}` is - greater than the given threshold `max_err_threshold` then the - segment is divided in two half. - - Intuitively, at positions with higher curvature, there must be - more points in order to improve approximation - quality. Theoretically toppra performs the best when the proposed - gridpoint is optimally distributed. - - @param maxErrThreshold Maximum worstcase error thrshold allowable. - @param maxIteration Maximum number of iterations. - @param maxSegLength All segments length should be smaller than this value. - @param minNbPoints Minimum number of points. - @param initialGridpoints Initial gridpoints to start the algorithm from. If - not provided, the path interval is used. If not empty, it must start - and end with the path interval limits. - @return The proposed gridpoints. - - */ - Vector proposeGridpoints(double maxErrThreshold=1e-4, int maxIteration=100, double maxSegLength=0.05, int minNbPoints=100, Vector initialGridpoints = Vector()) const; - - /** - * \brief Dimension of the configuration space - */ - int configSize() const - { - return m_configSize; - } - - /** - * \return the number of degrees-of-freedom of the path. - */ - int dof() const - { - return m_dof; - } - - /** - * \brief Serialize path to stream. - */ - virtual void serialize(std::ostream &O) const {}; - - /** - * \brief Deserialize stream to construct path. - */ - virtual void deserialize(std::istream &I){}; - - /** - * \brief Starting and ending path positions. - */ - virtual Bound pathInterval() const = 0; - - virtual ~GeometricPath() {} - - protected: - int m_configSize, m_dof; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp deleted file mode 100644 index e960eca1..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP -#define TOPPRA_PIECEWISE_POLY_PATH_HPP - -#include -#include -#include -#include - -namespace toppra { - - -struct BoundaryCond { - BoundaryCond() = default; - - /** - * @brief Construct a new BoundaryCond object with a manually specified derivative. - * - * @param order Order of the specified derivative. - * @param values Vector of values. Must have the same size as the path. - */ - BoundaryCond(int order, const std::vector &values); - - BoundaryCond(int order, const Vector values); - - /** - * @brief Construct a new Boundary Cond object with well-known boundary condition. - * - * @param bc_type Possible values: not-a-knot, clamped, natural and manual. - */ - BoundaryCond(std::string bc_type); - - enum Type { NotAKnot, Clamped, Natural, Manual}; - Type bc_type = NotAKnot; - int order = 0; - Vector values; -}; - -using BoundaryCondFull = std::array; - - -/** - * \brief Piecewise polynomial geometric path. - * - * An implementation of a piecewise polynomial geometric path. - * - * The coefficient vector has shape (N, P, D), where N is the number - * segments. For each segment, the i-th row (P index) denotes the - * power, while the j-th column is the degree of freedom. In - * particular, - * - * coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3) - * - * - */ -class PiecewisePolyPath : public GeometricPath { - public: - PiecewisePolyPath() = default; - - /** - * \brief Construct new piecewise polynomial. - * - * See class docstring for details. - * - * @param coefficients Polynomial coefficients. - * @param breakpoints Vector of breakpoints. - */ - PiecewisePolyPath(const Matrices &coefficients, std::vector breakpoints); - - /** - * /brief Evaluate the path at given position. - */ - Vector eval_single(value_type, int order = 0) const override; - - /** - * /brief Evaluate the path at given positions (vector). - */ - Vectors eval(const Vector &, int order = 0) const override; - - /** - * Return the starting and ending path positions. - */ - Bound pathInterval() const override; - void serialize(std::ostream &O) const override; - void deserialize(std::istream &I) override; - - /** - * @brief Construct a piecewise Cubic Hermite polynomial. - * - * See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for a good - * description of this interplation scheme. - * - * This function is implemented based on scipy.interpolate.CubicHermiteSpline. - * - * Note that path generates by this function is not guaranteed to have - * continuous acceleration, or the path second-order derivative. - * - * @param positions Robot joints corresponding to the given times. Must have - * the same size as times. - * @param velocities Robot joint velocities. - * @param times Path positions or times. This is the independent variable. - * @return PiecewisePolyPath - */ - static PiecewisePolyPath - CubicHermiteSpline(const Vectors &positions, const Vectors &velocities, - const std::vector times); - - TOPPRA_DEPRECATED static PiecewisePolyPath - constructHermite(const Vectors &positions, const Vectors &velocities, - const std::vector times); - - - /** - * @brief Construct a cubic spline. - * - * Interpolate the given joint positions with a spline that is twice - * continuously differentiable. This means the position, velocity and - * acceleration are guaranteed to be continous but not jerk. - * - * This method is modelled after scipy.interpolate.CubicSpline. - * - * @param positions Robot joints corresponding to the given times. - * @param times Path positions or times. This is the independent variable. - * @param bc_type Boundary condition. Currently on fixed boundary condition. - * @return PiecewisePolyPath - */ - static PiecewisePolyPath CubicSpline(const Vectors &positions, const Vector ×, BoundaryCondFull bc_type); - -private: - - /** - * @brief Calculate coefficients for Hermite spline. - * - * @param positions See the constructor. - * @param velocities - * @param times - */ - void initAsHermite(const Vectors &positions, const Vectors &velocities, - const std::vector times); - -protected: - static void computeCubicSplineCoefficients(const Vectors &positions, - const Vector ×, - const BoundaryCondFull &bc_type, - Matrices &coefficients); - // static void checkInputArgs(const Vectors &positions, const Vector ×, - // const BoundaryCondFull &bc_type); - - // Cubic spline - void reset(); - size_t findSegmentIndex(value_type pos) const; - void checkInputArgs(); - void computeDerivativesCoefficients(); - const Matrix &getCoefficient(size_t seg_index, int order) const; - Matrices m_coefficients, m_coefficients_1, m_coefficients_2; - std::vector m_breakpoints; - int m_degree; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp deleted file mode 100644 index d5dea633..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef TOPPRA_PARAMETRIZER_HPP -#define TOPPRA_PARAMETRIZER_HPP - -#include -#include - -namespace toppra { - -/** - * \brief Abstract output trajectory parametrizers. - * - * A parametrizer has the same interface as a geometric path. It - * receives as input the original geometric path and two arrays of - * gridpoints and parametrization (i.e. squared path velocities). A - * parametrizer should validate the input data. If not validated, - * evaluation results are not defined. - * - * Requirements: https://github.com/hungpham2511/toppra/issues/102 - * - * Sub-classes should override the virtual private methods *_impl. - */ -class Parametrizer : public GeometricPath { - public: - /** Construct the parametrizer. - * - * \param path Input geometric path. - * \param gridpoints Shape (N+1,). Gridpoints of the parametrization, should be - * compatible with the path domain. \param vsquared Shape (N+1,). Path velocity - * squared, should have same shape as gridpoints as vsquared[i] corresponds to the - * velocity at gridpoints[i]. - */ - Parametrizer(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - /** \brief Evaluate the path at given position. - */ - Vector eval_single(value_type, int order = 0) const override; - - /** \brief Evaluate the path at given positions (vector). - */ - Vectors eval(const Vector &, int order = 0) const override; - - /** \brief Return the starting and ending path positions. - */ - Bound pathInterval() const override; - - /** \brief Validate input data. - * - * Return false if something is wrong with the output - * trajectory. Only use the trajectory if validation successes. - */ - bool validate() const; - - virtual ~Parametrizer() {} - - /** \brief Return the waypoint times. - */ - virtual const Vector& getTimes() const = 0; - - protected: - // Input geometric path - GeometricPathPtr m_path; - // Input gridpoints - Vector m_gridpoints; - // Input path velocities (not squared) - Vector m_vs; - - private: - /// To be overwriten by derived classes - virtual Vectors eval_impl(const Vector &, int order = 0) const = 0; - virtual bool validate_impl() const = 0; - virtual Bound pathInterval_impl() const = 0; -}; -}; // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp deleted file mode 100644 index 7911671f..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef TOPPRA_CONST_ACCEL_HPP -#define TOPPRA_CONST_ACCEL_HPP - -#include -#include - -namespace toppra { - -namespace parametrizer { - -/** \brief A path parametrizer with constant acceleration assumption. - * - * We assume that in each segment, the path acceleration is constant. - */ -class ConstAccel : public Parametrizer { - public: - ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - const Vector& getTimes() const override { return m_ts; } - - private: - /** Return joint derivatives at specified times. */ - Vectors eval_impl(const Vector ×, int order = 0) const override; - bool validate_impl() const override; - Bound pathInterval_impl() const override; - - /** \brief Evaluate path variables ss, vs, and us at the input time instances. - * - * For each t, a starting gridpoint will be selected. The selected - * path position, velocity and acceleration is then used to compute - * the corresponding output quantities. - * - * \param[in] ts Time instances to be evaluated, starting from zero seconds. - * \param[out] ss Path positions at the given time instances. - * \param[out] vs Path velocities at the given time instances. - * \param[out] us Path accelerations at the given time instances. - * - */ - bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const; - // Compute times and acclerations from given data (path, velocities) - void process_internals(); - // Vector of time instances (corresponded to gridpoints) - Vector m_ts; - // Vector of accelerations (corresponded to gridpoints). Should have size - // shorter than m_ts and m_vs by 1. - Vector m_us; -}; -} // namespace parametrizer - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp deleted file mode 100644 index a5267255..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef TOPPRA_SPLINE_HPP -#define TOPPRA_SPLINE_HPP - -#include -#include - -namespace toppra { - -namespace parametrizer { - -/** \brief A path parametrizer via a spline interpolation. - * - * This class computes the time and position at each gridpoint, then - fit and return a CubicSpline (continuous first and second - derivatives). Note that the boundary conditions are: first - derivatives at the start and end of the path equal q(s)' * s'. - */ -class Spline: public Parametrizer { -public: - /** - * \brief Construct the spline parametrizer. - * - * See class docstring for details. - * - * @param path the input geometric path. - * @param gridpoints of the parametrization with shape (N+1,). - * @param vsquared the path velocity squared with shape (N+1,). - */ - Spline(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - const Vector& getTimes() const override { return m_ts; } - -private: - /** Return joint derivatives at specified times. */ - Vectors eval_impl(const Vector ×, int order = 0) const override; - bool validate_impl() const override; - Bound pathInterval_impl() const override; - - // Vector of time instances (corresponded to gridpoints) - Vector m_ts; -}; - -} // namespace parametrizer - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp deleted file mode 100644 index 8e2e196a..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp +++ /dev/null @@ -1,138 +0,0 @@ -#ifndef TOPPRA_SOLVER_HPP -#define TOPPRA_SOLVER_HPP - -#include - -namespace toppra { - -/** \brief The base class for all solver wrappers. - * - * All Solver can solve Linear/Quadratic Program subject to linear constraints - * at the given stage, and possibly with additional auxiliary constraints. - * - * All Solver derived class implements - * - Solver::solveStagewiseOptim: core method needed by all Reachability - * Analysis-based algorithms - * - Solver::setupSolver, Solver::closeSolver: needed by some Solver - * implementation, such as mosek and qpOASES with warmstart. - * - * Note that some Solver only handle Linear Program while - * some handle both. - * - * Each solver wrapper should provide solver-specific constraint, - * such as ultimate bound the variable u, x. For some solvers such as - * ECOS, this is very important. - * - * */ -class Solver { - public: - /// \brief Create a solver based on the compilation option. - /// At the time of writing, the preference order is - /// - qpOASES - /// - GLPK - /// If none of these is available, this function returns a null pointer. - static SolverPtr createDefault(); - - /// \copydoc Solver::m_deltas - const Vector& deltas () const - { - return m_deltas; - } - - /// \copydoc Solver::m_N - std::size_t nbStages () const - { - return m_N; - } - - /// \copydoc Solver::m_nV - std::size_t nbVars () const - { - return m_nV; - } - - /** Solve a stage-wise quadratic (or linear) optimization problem. - * - * The quadratic optimization problem is described below: - * - * \f{eqnarray} - * \text{min } & 0.5 [u, x, v] H [u, x, v]^\top + [u, x, v] g \\ - * \text{s.t. } & [u, x] \text{ is feasible at stage } i \\ - * & x_{min} \leq x \leq x_{max} \\ - * & x_{next, min} \leq x + 2 \Delta_i u \leq x_{next, max}, - * \f} - * - * where `v` is an auxiliary variable, only exist if there are - * non-canonical constraints. The linear program is the - * quadratic problem without the quadratic term. - * - * \param i The stage index. - * \param H Either a matrix of size (d, d), where d is \ref nbVars, in - * which case a quadratic objective is defined, or a matrix - * of size (0,0), in which case a linear objective is defined. - * \param g Vector of size \ref nbVars. The linear term. - * \param[out] solution in case of success, stores the optimal solution. - * - * \return whether the resolution is successful, in which case \c solution - * contains the optimal solution. - * */ - virtual bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution) = 0; - - /// \brief Initialize the solver - /// \note Child classes should call the parent implementation. - virtual void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - /** \brief Initialize the wrapped solver - */ - virtual void setupSolver () - {} - - /** \brief Free the wrapped solver - */ - virtual void closeSolver () - {} - - virtual ~Solver () {} - - protected: - Solver () {} - - void init (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - struct LinearConstraintParams { - int cid; - Vectors a, b, c, g; - Matrices F; - }; - struct BoxConstraintParams { - int cid; - Bounds u, x; - }; - struct ConstraintsParams { - std::vector lin; - std::vector box; - } m_constraintsParams; - - LinearConstraintPtrs m_constraints; - GeometricPathPtr m_path; - Vector m_times; - - private: - /// \brief Number of stages. - /// The number of gridpoints equals N + 1, where N is the number of stages. - std::size_t m_N; - /// Total number of variables, including u, x. - std::size_t m_nV; - /// Time increment between each stage. Size \ref nbStages - Vector m_deltas; - -}; // class Solver - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp deleted file mode 100644 index d0eefabd..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef TOPPRA_SOLVER_GLPK_WRAPPER_HPP -#define TOPPRA_SOLVER_GLPK_WRAPPER_HPP - -#include -#include - -// Forward declare glpk solver. -struct glp_prob; - -namespace toppra { -namespace solver { - -/** Wrapper around GLPK library. - * - * Internally, the problem is formulated as - * \f{eqnarray} - * min & g^T y \\ - * s.t & z = A y \\ - * & x_{min} <= x <= x_{max} \\ - * & l_1 <= z <= h_1 \\ - * \f} - * where - * \f{eqnarray} - * y =& \begin{pmatrix} u & x \end{pmatrix}^T \\ - * A =& \begin{pmatrix} - * 2\delta & 1 \\ - * F_i a_i & F_i b_i \\ - * \vdots & \vdots \\ - * \end{pmatrix}\\ - * \f} - * - * */ -class GLPKWrapper : public Solver { - public: - GLPKWrapper () = default; - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - virtual ~GLPKWrapper(); - - private: - glp_prob* m_lp = NULL; -}; // class GLPKWrapper - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp deleted file mode 100644 index bd490472..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef TOPPRA_SOLVER_QPOASES_WRAPPER_HPP -#define TOPPRA_SOLVER_QPOASES_WRAPPER_HPP - -#include -#include - -namespace toppra { -namespace solver { - -/** Wrapper around qpOASES::SQProblem - * - * Internally, the problem is formulated as - * \f{eqnarray} - * min & 0.5 y^T H y + g^T y \\ - * s.t & lA <= Ay <= hA \\ - * & l <= y <= h \\ - * \f} - * - * \todo Add a solver that inherits from qpOASESWrapper and that uses the warm - * start capabilities of qpOASES - * - * */ -class qpOASESWrapper : public Solver { - public: - qpOASESWrapper (); - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - virtual ~qpOASESWrapper(); - - value_type setBoundary () const - { - return m_boundary; - } - - void setBoundary (const value_type& v) - { - m_boundary = v; - } - - static void setDefaultBoundary (const value_type& v); - - private: - /// qpOASES uses row-major storage order. - typedef Eigen::Matrix RMatrix; - RMatrix m_H, m_A; - Vector m_lA, m_hA; - value_type m_boundary; - - static value_type m_defaultBoundary; - - struct Impl; - std::unique_ptr m_impl; -}; // class qpOASESWrapper - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp deleted file mode 100644 index c953e0ac..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef TOPPRA_SOLVER_SEIDEL_HPP -#define TOPPRA_SOLVER_SEIDEL_HPP - -#include -#include -#include - -namespace toppra { -namespace solver { - -/** Implementation of Seidel algorithm. - * - * */ -class Seidel : public Solver { - public: - Seidel () = default; - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - private: - typedef Eigen::Matrix MatrixX2; - typedef Eigen::Matrix MatrixX3; - typedef std::vector > MatricesX3; - - MatricesX3 m_A; - MatrixX2 m_low, m_high; - - MatrixX3 m_A_ordered; - MatrixX2 m_A_1d; - std::vector m_index_map; - std::array m_active_c_up, m_active_c_down; -}; // class Seidel - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp deleted file mode 100644 index ce9525de..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_TOPPRA_HPP -#define TOPPRA_TOPPRA_HPP - -#include -#include -#include -#include - -#include -#include - -#include - - -#ifdef TOPPRA_DEBUG_ON -#define TOPPRA_LOG_DEBUG(X) std::cout << "[DEBUG]: " << X << std::endl -#else -#define TOPPRA_LOG_DEBUG(X) ((void)0) -#endif - -#if defined(TOPPRA_DEBUG_ON) || defined(TOPPRA_WARN_ON) -#define TOPPRA_LOG_WARN(X) std::cout << "[WARN]: " << X << std::endl -#else -#define TOPPRA_LOG_WARN(X) ((void)0) -#endif - -#define TOPPRA_UNUSED(x) (void)(x) - -// Use for checking if a quantity is very close to zero -#define TOPPRA_NEARLY_ZERO 1e-8 -#define TOPPRA_REL_TOL 1e-6 -#define TOPPRA_ABS_TOL 1e-8 - - -/// The TOPP-RA namespace -namespace toppra { - /// The scalar type - typedef double value_type; - - constexpr value_type infty = std::numeric_limits::infinity(); - - /// Column vector type - typedef Eigen::Matrix Vector; - /// Matrix type - typedef Eigen::Matrix Matrix; - - /// Vector of Vector - typedef std::vector > Vectors; - /// Vector of Matrix - typedef std::vector > Matrices; - - // internal data rep for Matrix - typedef std::tuple> MatrixData; - typedef std::vector MatricesData; - - /// 2D vector that stores the upper and lower bound of a variable. - typedef Eigen::Matrix Bound; - /// Vector of Bound - typedef std::vector > Bounds; - - class LinearConstraint; - /// Shared pointer to a LinearConstraint - typedef std::shared_ptr LinearConstraintPtr; - /// Vector of LinearConstraintPtr - typedef std::vector LinearConstraintPtrs; - namespace constraint { - class LinearJointVelocity; - class LinearJointAcceleration; - class JointTorque; - } // namespace constraint - - class Solver; - typedef std::shared_ptr SolverPtr; - namespace solver { - class qpOASESWrapper; - } // namespace solver - - class GeometricPath; - typedef std::shared_ptr GeometricPathPtr; - - class PathParametrizationAlgorithm; - typedef std::shared_ptr PathParametrizationAlgorithmPtr; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake deleted file mode 100644 index 85f1a594..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake +++ /dev/null @@ -1,13 +0,0 @@ -set(TOPPRA_WITH_PINOCCHIO OFF) -set(TOPPRA_WITH_qpOASES OFF) -set(TOPPRA_WITH_GLPK OFF) - -find_package(Eigen3 REQUIRED) - -if(TOPPRA_WITH_PINOCCHIO) - find_package(pinocchio REQUIRED) -endif() -# qpOASES and GLPK do not need to be found again, because -# they are not used as targets. - -include("${CMAKE_CURRENT_LIST_DIR}/toppraTargets.cmake") diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake deleted file mode 100644 index b559b040..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake +++ /dev/null @@ -1,19 +0,0 @@ -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Import target "toppra::toppra" for configuration "" -set_property(TARGET toppra::toppra APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) -set_target_properties(toppra::toppra PROPERTIES - IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libtoppra.so" - IMPORTED_SONAME_NOCONFIG "libtoppra.so" - ) - -list(APPEND _cmake_import_check_targets toppra::toppra ) -list(APPEND _cmake_import_check_files_for_toppra::toppra "${_IMPORT_PREFIX}/lib/libtoppra.so" ) - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake deleted file mode 100644 index 2e6e57ae..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake +++ /dev/null @@ -1,107 +0,0 @@ -# Generated by CMake - -if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8) - message(FATAL_ERROR "CMake >= 2.8.0 required") -endif() -if(CMAKE_VERSION VERSION_LESS "2.8.12") - message(FATAL_ERROR "CMake >= 2.8.12 required") -endif() -cmake_policy(PUSH) -cmake_policy(VERSION 2.8.12...3.28) -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Protect against multiple inclusion, which would fail when already imported targets are added once more. -set(_cmake_targets_defined "") -set(_cmake_targets_not_defined "") -set(_cmake_expected_targets "") -foreach(_cmake_expected_target IN ITEMS toppra::toppra) - list(APPEND _cmake_expected_targets "${_cmake_expected_target}") - if(TARGET "${_cmake_expected_target}") - list(APPEND _cmake_targets_defined "${_cmake_expected_target}") - else() - list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}") - endif() -endforeach() -unset(_cmake_expected_target) -if(_cmake_targets_defined STREQUAL _cmake_expected_targets) - unset(_cmake_targets_defined) - unset(_cmake_targets_not_defined) - unset(_cmake_expected_targets) - unset(CMAKE_IMPORT_FILE_VERSION) - cmake_policy(POP) - return() -endif() -if(NOT _cmake_targets_defined STREQUAL "") - string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}") - string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}") - message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n") -endif() -unset(_cmake_targets_defined) -unset(_cmake_targets_not_defined) -unset(_cmake_expected_targets) - - -# Compute the installation prefix relative to this file. -get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -if(_IMPORT_PREFIX STREQUAL "/") - set(_IMPORT_PREFIX "") -endif() - -# Create imported target toppra::toppra -add_library(toppra::toppra SHARED IMPORTED) - -set_target_properties(toppra::toppra PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include" - INTERFACE_LINK_LIBRARIES "Eigen3::Eigen" -) - -# Load information for each installed configuration. -file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/toppraTargets-*.cmake") -foreach(_cmake_config_file IN LISTS _cmake_config_files) - include("${_cmake_config_file}") -endforeach() -unset(_cmake_config_file) -unset(_cmake_config_files) - -# Cleanup temporary variables. -set(_IMPORT_PREFIX) - -# Loop over all imported files and verify that they actually exist -foreach(_cmake_target IN LISTS _cmake_import_check_targets) - if(CMAKE_VERSION VERSION_LESS "3.28" - OR NOT DEFINED _cmake_import_check_xcframework_for_${_cmake_target} - OR NOT IS_DIRECTORY "${_cmake_import_check_xcframework_for_${_cmake_target}}") - foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}") - if(NOT EXISTS "${_cmake_file}") - message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file - \"${_cmake_file}\" -but this file does not exist. Possible reasons include: -* The file was deleted, renamed, or moved to another location. -* An install or uninstall procedure did not complete successfully. -* The installation package was faulty and contained - \"${CMAKE_CURRENT_LIST_FILE}\" -but not all the files it references. -") - endif() - endforeach() - endif() - unset(_cmake_file) - unset("_cmake_import_check_files_for_${_cmake_target}") -endforeach() -unset(_cmake_target) -unset(_cmake_import_check_targets) - -# This file does not depend on other imported targets which have -# been exported from the same project but in a separate export set. - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) -cmake_policy(POP) diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so b/dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so deleted file mode 100644 index 374a1911..00000000 Binary files a/dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so and /dev/null differ 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