feat(arm): sync TCHL motion stack and release build workflow
Integrate lgv_dev_tc_motor arm planning dependencies while retaining linbo_dev capabilities. Configure seven TCHL axes, preserve existing limits and igc startup defaults, and sync build script updates through 08d9a393.
This commit is contained in:
parent
10c1c891e1
commit
c571b476a1
@ -67,7 +67,7 @@ find_package(protobuf REQUIRED)
|
||||
find_package(gRPC REQUIRED)
|
||||
|
||||
############################################################
|
||||
# PROTO , 遇到proto 的生成问题,现在build 目录执行 cmake --install . --verbose ,然后编译即可
|
||||
# PROTO
|
||||
############################################################
|
||||
|
||||
set(PROTO_IMPORT_DIR ${PROJECT_SOURCE_DIR}/protos)
|
||||
@ -76,9 +76,10 @@ file(MAKE_DIRECTORY ${PROTO_BINARY_DIR})
|
||||
file(GLOB_RECURSE PROTO_FILES ${PROTO_IMPORT_DIR}/*.proto)
|
||||
|
||||
|
||||
set(Protobuf_PROTOC_EXECUTABLE "${CMAKE_INSTALL_PREFIX}/bin/protoc" CACHE FILEPATH "" FORCE)
|
||||
set_property(TARGET gRPC::grpc_cpp_plugin
|
||||
PROPERTY IMPORTED_LOCATION "${CMAKE_INSTALL_PREFIX}/bin/grpc_cpp_plugin"
|
||||
# Run bundled tools with their libraries, without requiring output/bin first.
|
||||
set(PROTOC_COMMAND_OPTIONS -E env
|
||||
"LD_LIBRARY_PATH=$<TARGET_FILE_DIR:protobuf::libprotobuf>"
|
||||
"$<TARGET_FILE:protobuf::protoc>"
|
||||
)
|
||||
|
||||
# 1) 先做 OBJECT:只负责生成/编译 pb.cc
|
||||
@ -88,12 +89,16 @@ set_target_properties(proto-objects PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
protobuf_generate(
|
||||
TARGET proto-objects
|
||||
PROTOC_EXE "${CMAKE_COMMAND}"
|
||||
PROTOC_OPTIONS ${PROTOC_COMMAND_OPTIONS}
|
||||
IMPORT_DIRS ${PROTO_IMPORT_DIR}
|
||||
PROTOC_OUT_DIR ${PROTO_BINARY_DIR}
|
||||
USAGE_REQUIREMENT PRIVATE
|
||||
)
|
||||
protobuf_generate(
|
||||
TARGET proto-objects
|
||||
PROTOC_EXE "${CMAKE_COMMAND}"
|
||||
PROTOC_OPTIONS ${PROTOC_COMMAND_OPTIONS}
|
||||
LANGUAGE grpc
|
||||
GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc
|
||||
PLUGIN "protoc-gen-grpc=$<TARGET_FILE:gRPC::grpc_cpp_plugin>"
|
||||
|
||||
77
README.md
77
README.md
@ -4,6 +4,15 @@
|
||||
|
||||
CMVR-ES 工程。
|
||||
|
||||
机械臂已提供独立的 OMPL RRTConnect 关节路径规划模块。`MotorRobotArm::moveP` 已接入路径规划、
|
||||
五次 B 样条平滑、运动限值校验与碰撞复检,并按控制周期下发电机指令。
|
||||
|
||||
运行时自碰撞监测位于 `cmvr-es/safety/self_collision`:`SelfCollisionMonitor`
|
||||
通过 `RobotArm` 接口读取反馈、触发保护停止并协调恢复,碰撞计算仍由
|
||||
`algorithms/collision_detection` 中的 `CollisionChecker` 完成。
|
||||
`SelfCollisionTask` 仅绑定机械臂和转发周期调度;Monitor 不创建线程,恢复调用期间
|
||||
须继续周期检测。现有 `self_collision_task` 配置格式保持不变。
|
||||
|
||||
## 安装
|
||||
|
||||
### 1. 拉取 Git 子模块
|
||||
@ -58,6 +67,9 @@ sudo apt install gnuplot-qt
|
||||
dependency/x86/third_party/ethercat/v1.7.0
|
||||
```
|
||||
|
||||
当前依赖的源码提交和配套内核版本记录在该目录的 `BUILDINFO.txt` 中。
|
||||
目录中保留的其他内核版本模块不代表与当前 userspace 兼容。
|
||||
|
||||
先设置本机路径:
|
||||
|
||||
```shell
|
||||
@ -72,7 +84,8 @@ sudo apt-get update
|
||||
sudo apt-get install -y linux-headers-$(uname -r)
|
||||
```
|
||||
|
||||
如果内置目录里已经有当前内核版本的 EtherCAT 内核模块,直接安装到系统:
|
||||
只有在内置 userspace(`libethercat.so`、`ecrt.h`)与 EtherCAT 内核模块来自
|
||||
同一个源码提交,并且模块对应当前内核版本时,才可以直接安装到系统:
|
||||
|
||||
```shell
|
||||
sudo mkdir -p /lib/modules/$(uname -r)/ethercat
|
||||
@ -80,7 +93,11 @@ sudo cp -r $IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)/ethercat/* /lib/modules/$(
|
||||
sudo depmod
|
||||
```
|
||||
|
||||
内置内核模块只适用于相同内核版本。如果 `$IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)` 不存在,说明这台机器的内核版本不匹配,需要在这台机器上重新编译安装 IgH EtherCAT:
|
||||
不能只根据 `uname -r` 和 IgH `1.7.0` 版本号判断兼容性。同一个稳定分支的不同
|
||||
提交也可能使用不同的 ioctl 数据结构,混用后会出现
|
||||
`Failed to create slave config: Inappropriate ioctl for device`。如果无法确认 userspace
|
||||
和内核模块来自同一提交,或者 `$IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)` 不存在,
|
||||
需要在这台机器上使用同一份源码重新编译安装 IgH EtherCAT:
|
||||
|
||||
```shell
|
||||
sudo apt-get update
|
||||
@ -91,6 +108,7 @@ sudo apt-get install -y \
|
||||
cd /tmp
|
||||
git clone --branch stable-1.7 --depth 1 https://gitlab.com/etherlab.org/ethercat.git ethercat-stable-1.7
|
||||
cd ethercat-stable-1.7
|
||||
git rev-parse HEAD # 记录本次 userspace 和内核模块共同使用的提交
|
||||
|
||||
./bootstrap
|
||||
./configure \
|
||||
@ -108,10 +126,30 @@ sudo make modules_install
|
||||
sudo depmod
|
||||
```
|
||||
|
||||
其中,`make install` 会更新 `$IGH_ETHERCAT_ROOT` 下的用户态库、头文件和工具,
|
||||
也会覆盖该目录中的默认配置文件;已有网卡配置应先备份并在安装后恢复。
|
||||
`sudo make modules_install` 会更新 `/lib/modules/$(uname -r)/ethercat` 下的
|
||||
`ec_master.ko`、`ec_generic.ko` 等内核模块。已加载的模块需要通过下方启动脚本
|
||||
停止并重新加载后才会使用新文件;执行前应退出正在占用主站的应用。
|
||||
|
||||
安装完成后,检查用户态库与内核模块中的“创建 slave config” ioctl 编号。
|
||||
使用 `libethercat.so.1` 符号链接,避免把实际库文件名固定为旧的 `1.2.0`:
|
||||
|
||||
```shell
|
||||
objdump -d --disassemble=ecrt_master_slave_config "$IGH_ETHERCAT_ROOT/lib/libethercat.so.1" \
|
||||
| rg -o -m1 '\$0x[cC][0-9a-fA-F]+a423'
|
||||
|
||||
objdump -d "/lib/modules/$(uname -r)/ethercat/master/ec_master.ko" \
|
||||
| rg -o -m1 '\$0x[cC][0-9a-fA-F]+a423'
|
||||
```
|
||||
|
||||
两条命令的输出必须完全一致。编号不同说明 ABI 不兼容,不能启动 EtherCAT 应用;
|
||||
编号一致是必要检查,仍需保证用户态和内核模块来自同一源码提交。
|
||||
|
||||
启动 EtherCAT。`eno1` 换成实际连接 EtherCAT 从站的网卡:
|
||||
|
||||
```shell
|
||||
sudo script/ethercat/start_ethercat.sh eno1
|
||||
sudo scripts/ethercat/start_ethercat.sh eno1
|
||||
```
|
||||
|
||||
脚本会写入内置 IgH 配置文件:
|
||||
@ -125,7 +163,7 @@ $IGH_ETHERCAT_ROOT/etc/ethercat.conf
|
||||
查看状态:
|
||||
|
||||
```shell
|
||||
script/ethercat/status_ethercat.sh
|
||||
scripts/ethercat/status_ethercat.sh
|
||||
|
||||
$IGH_ETHERCAT_ROOT/bin/ethercat master
|
||||
$IGH_ETHERCAT_ROOT/bin/ethercat slaves
|
||||
@ -135,6 +173,33 @@ $IGH_ETHERCAT_ROOT/bin/ethercat pdos
|
||||
停止 EtherCAT:
|
||||
|
||||
```shell
|
||||
sudo script/ethercat/stop_ethercat.sh eno1
|
||||
sudo script/ethercat/stop_ethercat.sh eno1 --restore-network
|
||||
sudo scripts/ethercat/stop_ethercat.sh eno1
|
||||
sudo scripts/ethercat/stop_ethercat.sh eno1 --restore-network
|
||||
```
|
||||
|
||||
### 4. 编译并安装
|
||||
|
||||
项目脚本统一位于 `scripts/`,用途见 [脚本索引](scripts/README.md)。
|
||||
|
||||
在项目根目录执行,不传参数默认使用 `Debug`,也可显式选择构建类型:
|
||||
|
||||
```shell
|
||||
./scripts/build.sh
|
||||
./scripts/build.sh Debug
|
||||
./scripts/build.sh Release
|
||||
./scripts/build.sh RelWithDebInfo
|
||||
```
|
||||
|
||||
三种类型分别使用 `build/Debug`、`build/Release`、`build/RelWithDebInfo`,
|
||||
重复执行会增量编译。编译成功后自动安装到 `output`;编译失败不会执行安装。
|
||||
日常运行和性能测试建议使用 `RelWithDebInfo`,保留调试信息并开启优化。
|
||||
预编译的第三方库直接复用,不会随构建类型重新编译。
|
||||
|
||||
默认使用 4 个编译任务,可通过环境变量调整:
|
||||
|
||||
```shell
|
||||
CMAKE_BUILD_PARALLEL_LEVEL=2 ./scripts/build.sh RelWithDebInfo
|
||||
```
|
||||
|
||||
安装会更新 `output/bin`、`output/lib`,并用源码目录的配置和模型替换
|
||||
`output/bin/config`、`output/bin/model`;需要保留的配置应修改在源码目录中。
|
||||
|
||||
@ -3,6 +3,8 @@ link_libraries(cmvr_es::logging)
|
||||
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(hardware)
|
||||
add_subdirectory(curves)
|
||||
add_subdirectory(environment)
|
||||
add_subdirectory(algorithms)
|
||||
add_subdirectory(simulate)
|
||||
add_subdirectory(devices)
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
add_subdirectory(motion_planner)
|
||||
add_subdirectory(planner)
|
||||
add_subdirectory(smoother)
|
||||
add_subdirectory(kinematics/ik_solver)
|
||||
add_subdirectory(perception)
|
||||
add_subdirectory(controllers)
|
||||
|
||||
@ -46,3 +46,49 @@ target_compile_definitions(self_collision_benchmark PRIVATE
|
||||
)
|
||||
|
||||
install(TARGETS self_collision_checker LIBRARY DESTINATION lib)
|
||||
|
||||
add_library(collision_checker SHARED
|
||||
src/collision_checker.cpp
|
||||
src/distance_sampling_policy.cpp
|
||||
)
|
||||
|
||||
target_include_directories(collision_checker PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
target_compile_definitions(collision_checker PRIVATE
|
||||
COAL_DISABLE_HPP_FCL_WARNINGS
|
||||
)
|
||||
|
||||
target_link_libraries(collision_checker PUBLIC
|
||||
cmvr_es::environment
|
||||
cmvr_es::proto
|
||||
)
|
||||
target_link_libraries(collision_checker PRIVATE coal)
|
||||
|
||||
add_library(cmvr_es::collision_checker ALIAS collision_checker)
|
||||
|
||||
add_executable(collision_checker_test
|
||||
test/collision_checker_test.cpp
|
||||
)
|
||||
target_link_libraries(collision_checker_test PRIVATE
|
||||
cmvr_es::collision_checker
|
||||
gtest
|
||||
gtest_main
|
||||
pthread
|
||||
)
|
||||
target_compile_definitions(collision_checker_test PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
|
||||
)
|
||||
|
||||
add_executable(lgv_collision_benchmark
|
||||
benchmark/collision_benchmark.cpp
|
||||
)
|
||||
target_link_libraries(lgv_collision_benchmark PRIVATE
|
||||
cmvr_es::collision_checker
|
||||
)
|
||||
target_compile_definitions(lgv_collision_benchmark PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
|
||||
)
|
||||
|
||||
install(TARGETS collision_checker LIBRARY DESTINATION lib)
|
||||
|
||||
@ -0,0 +1,53 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "algorithms/collision_detection/include/collision_checker.h"
|
||||
|
||||
int main()
|
||||
{
|
||||
const std::string urdf_path = std::string(CMVR_ES_SOURCE_DIR) +
|
||||
"/model/xiaoyan_description/dual_arm_collision.urdf";
|
||||
const std::vector<std::string> joint_names{
|
||||
"R_SHOULDER_P", "R_SHOULDER_R", "R_SHOULDER_Y", "R_ELBOW_R",
|
||||
"R_WRIST_P", "R_WRIST_Y", "R_WRIST_R",
|
||||
};
|
||||
|
||||
cmvr::CollisionChecker checker;
|
||||
std::string error;
|
||||
if (!checker.init(urdf_path, joint_names, {}, &error)) {
|
||||
std::cerr << "Initialization failed: " << error << '\n';
|
||||
return 1;
|
||||
}
|
||||
|
||||
constexpr std::size_t kIterations = 2000;
|
||||
std::vector<double> samples_us;
|
||||
samples_us.reserve(kIterations);
|
||||
std::vector<double> q(joint_names.size(), 0.0);
|
||||
for (std::size_t iteration = 0; iteration < kIterations; ++iteration) {
|
||||
q[0] = 0.2 * static_cast<double>(iteration % 100) / 100.0;
|
||||
const auto begin = std::chrono::steady_clock::now();
|
||||
const auto result = checker.check(q);
|
||||
const auto end = std::chrono::steady_clock::now();
|
||||
if (!result.valid) {
|
||||
std::cerr << "Collision check failed: " << result.error << '\n';
|
||||
return 1;
|
||||
}
|
||||
samples_us.push_back(std::chrono::duration<double, std::micro>(end - begin).count());
|
||||
}
|
||||
|
||||
std::sort(samples_us.begin(), samples_us.end());
|
||||
double total_us = 0.0;
|
||||
for (const double sample : samples_us) {
|
||||
total_us += sample;
|
||||
}
|
||||
const std::size_t p99_index = static_cast<std::size_t>(0.99 * (samples_us.size() - 1));
|
||||
std::cout << "active_pairs=" << checker.activePairCount() << '\n'
|
||||
<< "iterations=" << samples_us.size() << '\n'
|
||||
<< "average_us=" << total_us / samples_us.size() << '\n'
|
||||
<< "p99_us=" << samples_us[p99_index] << '\n'
|
||||
<< "max_us=" << samples_us.back() << '\n';
|
||||
return 0;
|
||||
}
|
||||
@ -0,0 +1,131 @@
|
||||
#ifndef CMVR_ES_COLLISION_CHECKER_H
|
||||
#define CMVR_ES_COLLISION_CHECKER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Geometry>
|
||||
|
||||
#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<CollisionPair> ignored_pairs;
|
||||
// Copied at init; robot-world pairs are never excluded by ignored_pairs.
|
||||
std::vector<BoxObstacle> 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<bool(const std::vector<double>&)> additional_state_valid;
|
||||
std::function<bool()> 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<std::string>& active_joint_names,
|
||||
const CollisionOptions& options,
|
||||
std::string* error = nullptr);
|
||||
|
||||
bool init(const std::string& urdf_path,
|
||||
const std::vector<std::string>& 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<std::string>& 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<CollisionBody> collisionBodies(const std::vector<double>& joint_positions) const;
|
||||
|
||||
CollisionResult check(const std::vector<CollisionBody>& bodies);
|
||||
CollisionResult check(const std::vector<double>& joint_positions);
|
||||
|
||||
// Invalid queries throw; collisions and additional constraint failures
|
||||
// return false. Additional constraints cannot bypass geometry checks.
|
||||
bool isStateValid(const std::vector<double>& 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<std::string>& jointNames() const;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
#endif // CMVR_ES_COLLISION_CHECKER_H
|
||||
@ -0,0 +1,47 @@
|
||||
#ifndef CMVR_ES_DISTANCE_SAMPLING_POLICY_H
|
||||
#define CMVR_ES_DISTANCE_SAMPLING_POLICY_H
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
struct DistanceSamplingOptions {
|
||||
double max_geometry_displacement_m{0.002};
|
||||
double max_check_period_s{0.01};
|
||||
};
|
||||
|
||||
class LgvDistanceSamplingPolicy {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
bool configure(const DistanceSamplingOptions& options,
|
||||
std::string* error = nullptr);
|
||||
|
||||
bool shouldCheck(const std::vector<CollisionBody>& current,
|
||||
Clock::time_point now) const;
|
||||
|
||||
void markChecked(const std::vector<CollisionBody>& current,
|
||||
Clock::time_point now);
|
||||
|
||||
void reset();
|
||||
|
||||
double displacementSinceLastCheck(
|
||||
const std::vector<CollisionBody>& current) const;
|
||||
|
||||
bool hasBaseline() const { return has_baseline_; }
|
||||
|
||||
private:
|
||||
DistanceSamplingOptions options_{};
|
||||
std::vector<CollisionBody> last_checked_{};
|
||||
Clock::time_point last_check_time_{};
|
||||
bool configured_{false};
|
||||
bool has_baseline_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
#endif // CMVR_ES_DISTANCE_SAMPLING_POLICY_H
|
||||
468
cmvr-es/algorithms/collision_detection/src/collision_checker.cpp
Normal file
468
cmvr-es/algorithms/collision_detection/src/collision_checker.cpp
Normal file
@ -0,0 +1,468 @@
|
||||
#include "algorithms/collision_detection/include/collision_checker.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include <coal/distance.h>
|
||||
#include <coal/shape/geometric_shapes.h>
|
||||
|
||||
#include "cmvr/config/collision_config.pb.h"
|
||||
#include "common/config/config_files.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
using LinkPairKey = std::pair<std::string, std::string>;
|
||||
|
||||
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<std::string>& 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<double>(joint_names_.size(), 0.0), joint_names_);
|
||||
if (bodies.empty()) {
|
||||
return reject("No collision geometry remains after arm filtering");
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> 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<LinkPairKey> 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<std::string> 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<double>::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<coal::Box>(
|
||||
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<CollisionBody> collisionBodies(const std::vector<double>& 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<CollisionBody>& 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<double>::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<double>::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<double>& 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<const coal::CollisionGeometry> 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<QueryObject>& 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<std::string> joint_names_;
|
||||
RobotModel robot_model_;
|
||||
std::vector<std::size_t> geometry_indices_;
|
||||
std::vector<QueryObject> objects_;
|
||||
std::vector<DistancePair> pairs_;
|
||||
};
|
||||
|
||||
CollisionChecker::CollisionChecker()
|
||||
: impl_(std::make_unique<Impl>())
|
||||
{
|
||||
}
|
||||
|
||||
CollisionChecker::~CollisionChecker() = default;
|
||||
CollisionChecker::CollisionChecker(CollisionChecker&&) noexcept = default;
|
||||
CollisionChecker& CollisionChecker::operator=(CollisionChecker&&) noexcept = default;
|
||||
|
||||
bool CollisionChecker::init(const RobotModel& model,
|
||||
const std::vector<std::string>& 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<std::string>& 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<std::string>& 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<CollisionBody> CollisionChecker::collisionBodies(
|
||||
const std::vector<double>& joint_positions) const
|
||||
{
|
||||
return impl_->collisionBodies(joint_positions);
|
||||
}
|
||||
|
||||
CollisionResult CollisionChecker::check(const std::vector<CollisionBody>& bodies)
|
||||
{
|
||||
return impl_->check(bodies);
|
||||
}
|
||||
|
||||
CollisionResult CollisionChecker::check(const std::vector<double>& joint_positions)
|
||||
{
|
||||
return impl_->check(joint_positions);
|
||||
}
|
||||
|
||||
bool CollisionChecker::isStateValid(const std::vector<double>& 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<double> 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<std::string>& CollisionChecker::jointNames() const
|
||||
{
|
||||
return impl_->joint_names_;
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -0,0 +1,100 @@
|
||||
#include "algorithms/collision_detection/include/distance_sampling_policy.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
void setError(std::string* error, const std::string& message)
|
||||
{
|
||||
if (error) {
|
||||
*error = message;
|
||||
}
|
||||
}
|
||||
|
||||
double rotationAngle(const Eigen::Quaterniond& first,
|
||||
const Eigen::Quaterniond& second)
|
||||
{
|
||||
const double dot = std::clamp(
|
||||
std::abs(first.normalized().dot(second.normalized())), 0.0, 1.0);
|
||||
return 2.0 * std::acos(dot);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool LgvDistanceSamplingPolicy::configure(const DistanceSamplingOptions& options,
|
||||
std::string* error)
|
||||
{
|
||||
if (!std::isfinite(options.max_geometry_displacement_m) ||
|
||||
options.max_geometry_displacement_m <= 0.0) {
|
||||
setError(error, "max_geometry_displacement_m must be finite and positive");
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(options.max_check_period_s) ||
|
||||
options.max_check_period_s <= 0.0) {
|
||||
setError(error, "max_check_period_s must be finite and positive");
|
||||
return false;
|
||||
}
|
||||
options_ = options;
|
||||
configured_ = true;
|
||||
reset();
|
||||
if (error) {
|
||||
error->clear();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LgvDistanceSamplingPolicy::shouldCheck(const std::vector<CollisionBody>& current,
|
||||
const Clock::time_point now) const
|
||||
{
|
||||
if (!configured_ || !has_baseline_) {
|
||||
return true;
|
||||
}
|
||||
const double elapsed_s = std::chrono::duration<double>(now - last_check_time_).count();
|
||||
if (elapsed_s >= options_.max_check_period_s) {
|
||||
return true;
|
||||
}
|
||||
return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m;
|
||||
}
|
||||
|
||||
void LgvDistanceSamplingPolicy::markChecked(const std::vector<CollisionBody>& current,
|
||||
const Clock::time_point now)
|
||||
{
|
||||
last_checked_ = current;
|
||||
last_check_time_ = now;
|
||||
has_baseline_ = true;
|
||||
}
|
||||
|
||||
void LgvDistanceSamplingPolicy::reset()
|
||||
{
|
||||
last_checked_.clear();
|
||||
last_check_time_ = Clock::time_point{};
|
||||
has_baseline_ = false;
|
||||
}
|
||||
|
||||
double LgvDistanceSamplingPolicy::displacementSinceLastCheck(
|
||||
const std::vector<CollisionBody>& current) const
|
||||
{
|
||||
if (!has_baseline_ || current.size() != last_checked_.size()) {
|
||||
return std::numeric_limits<double>::infinity();
|
||||
}
|
||||
|
||||
double maximum_displacement = 0.0;
|
||||
for (std::size_t index = 0; index < current.size(); ++index) {
|
||||
const auto& previous = last_checked_[index];
|
||||
const auto& now = current[index];
|
||||
if (previous.geometry_index != now.geometry_index) {
|
||||
return std::numeric_limits<double>::infinity();
|
||||
}
|
||||
const double translation = (now.position - previous.position).norm();
|
||||
const double radius = std::max(previous.bounding_radius_m, now.bounding_radius_m);
|
||||
const double swept_distance =
|
||||
translation + radius * rotationAngle(previous.orientation, now.orientation);
|
||||
maximum_displacement = std::max(maximum_displacement, swept_distance);
|
||||
}
|
||||
return maximum_displacement;
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -0,0 +1,840 @@
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <initializer_list>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#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<std::string> 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<std::string> 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<double> kGen2SetupPose{
|
||||
0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0,
|
||||
};
|
||||
|
||||
const std::vector<double> kGen2WarningPose{
|
||||
2.45028525340088,
|
||||
0.413065394330014,
|
||||
-1.78610031118294,
|
||||
2.3232081721811,
|
||||
-2.96828882895788,
|
||||
-1.59350098130002,
|
||||
0.582912411114367,
|
||||
};
|
||||
|
||||
const std::vector<double> kGen2StopPose{
|
||||
2.13758633436379,
|
||||
1.61835160165575,
|
||||
-2.3836142221041,
|
||||
0.964538527544213,
|
||||
-0.00382525077004825,
|
||||
1.74586899135531,
|
||||
-0.336868659266887,
|
||||
};
|
||||
|
||||
const std::vector<double> kGen2CollisionPose{
|
||||
-0.42656969579233,
|
||||
1.41426471041774,
|
||||
-2.67949400419915,
|
||||
2.45814854129954,
|
||||
-2.35907388079205,
|
||||
1.14125209449898,
|
||||
1.53232912981414,
|
||||
};
|
||||
|
||||
const std::vector<double> 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<CollisionBody> 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"(<robot name="box_scene"><link name="base">)";
|
||||
if (base_collision) {
|
||||
file << R"(<collision><geometry><sphere radius="0.1"/></geometry></collision>)";
|
||||
}
|
||||
file << R"(</link>
|
||||
<link name="mount"/>
|
||||
<joint name="fixed_mount" type="fixed">
|
||||
<parent link="base"/><child link="mount"/>
|
||||
<origin xyz=")" << mount_x << R"( 0 0" rpy="0 0 1.5707963267948966"/>
|
||||
</joint>
|
||||
<link name="tip">)";
|
||||
if (tip_collision) {
|
||||
file << R"(<collision><geometry><sphere radius="0.05"/></geometry></collision>)";
|
||||
}
|
||||
file << R"(</link>
|
||||
<joint name="slide" type="prismatic">
|
||||
<parent link="mount"/><child link="tip"/><axis xyz="1 0 0"/>
|
||||
<limit lower="-2" upper="2" effort="1" velocity="1"/>
|
||||
</joint>
|
||||
</robot>)";
|
||||
}
|
||||
|
||||
~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<double> positions)
|
||||
{
|
||||
device::JointTrajectory trajectory;
|
||||
for (const double position : positions) {
|
||||
device::JointTrajectoryPoint point;
|
||||
point.time_s = static_cast<double>(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<std::string>{"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<double>{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<double>{position});
|
||||
const auto second_result = second.check(std::vector<double>{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<double>{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<std::string> joints;
|
||||
std::vector<double> position;
|
||||
CollisionOptions options;
|
||||
};
|
||||
const std::string root = CMVR_ES_SOURCE_DIR;
|
||||
for (const auto& test : std::vector<ModelCase>{
|
||||
{root + "/model/xiaoyan_description/dual_arm.urdf", collisionUrdfPath(),
|
||||
kRightArmJoints, std::vector<double>(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<std::vector<double>>{
|
||||
{}, {0.0, 1.0}, {std::numeric_limits<double>::quiet_NaN()},
|
||||
{std::numeric_limits<double>::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"(<robot name="continuous_test">
|
||||
<link name="base"/><link name="tip"/>
|
||||
<joint name="continuous_joint" type="continuous">
|
||||
<parent link="base"/><child link="tip"/><axis xyz="0 0 1"/>
|
||||
<limit effort="1" velocity="1"/>
|
||||
</joint>
|
||||
</robot>)");
|
||||
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<double>(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<double>(6, 0.0)));
|
||||
EXPECT_FALSE(checker.check(std::vector<double>(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<double>{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<double>{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<double>{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<double>{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<double>{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<double>{1.0}).in_collision);
|
||||
|
||||
options.obstacles.front().orientation.setIdentity();
|
||||
ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error;
|
||||
result = checker.check(std::vector<double>{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<double>::infinity(),
|
||||
std::numeric_limits<double>::quiet_NaN()}) {
|
||||
auto box = testBox();
|
||||
box.size_m.x() = value;
|
||||
reject(box);
|
||||
}
|
||||
auto box = testBox();
|
||||
box.position_m.y() = std::numeric_limits<double>::infinity();
|
||||
reject(box);
|
||||
box = testBox();
|
||||
box.orientation.coeffs().setZero();
|
||||
reject(box);
|
||||
box.orientation.x() = std::numeric_limits<double>::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<double> checked;
|
||||
options.additional_state_valid = [&](const std::vector<double>& 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<double>& 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<double>& 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<double>&) {
|
||||
++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<std::vector<double>>{
|
||||
{}, {0.0, 0.0}, {std::numeric_limits<double>::infinity()},
|
||||
{std::numeric_limits<double>::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<double>::infinity(),
|
||||
std::numeric_limits<double>::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<double>::infinity(),
|
||||
std::numeric_limits<double>::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<double>&) -> bool {
|
||||
throw std::runtime_error("TCP constraint query failed");
|
||||
};
|
||||
const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options);
|
||||
EXPECT_FALSE(result.valid);
|
||||
EXPECT_NE(result.error.find("TCP constraint query failed"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement)
|
||||
{
|
||||
LgvDistanceSamplingPolicy policy;
|
||||
DistanceSamplingOptions options;
|
||||
options.max_geometry_displacement_m = 0.002;
|
||||
options.max_check_period_s = 0.01;
|
||||
std::string error;
|
||||
ASSERT_TRUE(policy.configure(options, &error)) << error;
|
||||
|
||||
const auto start = LgvDistanceSamplingPolicy::Clock::now();
|
||||
const auto initial = singleBody(0.0, 0.0, 0.2);
|
||||
EXPECT_TRUE(policy.shouldCheck(initial, start));
|
||||
policy.markChecked(initial, start);
|
||||
|
||||
EXPECT_FALSE(policy.shouldCheck(
|
||||
singleBody(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleBody(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleBody(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
initial, start + std::chrono::milliseconds(10)));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr
|
||||
@ -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
|
||||
|
||||
@ -6,12 +6,12 @@
|
||||
#include <common/base/constants.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <Eigen/Core>
|
||||
#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<const UrdfParser> 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<std::string>& 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<const UrdfParser>& parser,
|
||||
bool initUrdfChain(const RobotModel& model,
|
||||
const std::string& base_frame_name,
|
||||
const std::string& tip_frame_name);
|
||||
|
||||
// 上次调用ik 时计算的结果
|
||||
std::vector<double> cur_joints_angle_{};
|
||||
|
||||
// URDF 解析器(用于统一管理链路限位/关节名)。
|
||||
std::shared_ptr<const UrdfParser> 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<std::string> chain_joint_names_{};
|
||||
|
||||
// 链路缓存是否有效。
|
||||
bool urdf_chain_cached_{false};
|
||||
|
||||
|
||||
@ -5,16 +5,16 @@
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Core>
|
||||
|
||||
#include <pinocchio/multibody/model.hpp>
|
||||
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
/**
|
||||
* @brief 基于 Pinocchio 的 URDF 解析工具类。
|
||||
* @brief 从已加载的 RobotModel 提取运动链信息。
|
||||
*
|
||||
* 主要职责:
|
||||
* - 加载 URDF 到 Pinocchio 模型
|
||||
* - 提取 base->tip 链路信息
|
||||
* - 输出链路 q/v 索引范围、关节顺序、位置/速度限位
|
||||
*/
|
||||
@ -64,39 +64,39 @@ public:
|
||||
std::vector<JointSegment> joints;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 加载 URDF 模型。
|
||||
* @param urdf_path URDF 文件路径。
|
||||
* @param error 可选错误信息输出。
|
||||
* @return 成功返回 true,失败返回 false。
|
||||
*/
|
||||
bool loadModel(const std::string& urdf_path, std::string* error = nullptr);
|
||||
|
||||
/**
|
||||
* @brief 提取 base->tip 链路信息。
|
||||
*
|
||||
* 实现方式:从 tip 的父关节向上回溯到 base 的父关节,
|
||||
* 再反转为 base->tip 顺序。
|
||||
*
|
||||
* @param robot_model 已加载运动学的机器人模型。
|
||||
* @param base_frame_name 基坐标系 frame 名称。
|
||||
* @param tip_frame_name 末端 frame 名称。
|
||||
* @param out 输出链路信息。
|
||||
* @param error 可选错误信息输出。
|
||||
* @return 成功返回 true,失败返回 false。
|
||||
*/
|
||||
bool extractChain(const std::string& base_frame_name,
|
||||
const std::string& tip_frame_name,
|
||||
ChainInfo& out,
|
||||
std::string* error = nullptr) const;
|
||||
|
||||
/** @brief 获取已加载的 Pinocchio 模型。 */
|
||||
const pinocchio::Model& model() const { return model_; }
|
||||
/** @brief 当前是否已成功加载模型。 */
|
||||
bool loaded() const { return loaded_; }
|
||||
static bool extractChain(const RobotModel& robot_model,
|
||||
const std::string& base_frame_name,
|
||||
const std::string& tip_frame_name,
|
||||
ChainInfo& out,
|
||||
std::string* error = nullptr);
|
||||
|
||||
// Compatibility for linbo_dev callers that own a standalone parser.
|
||||
bool loadModel(const std::string& path, std::string* error = nullptr) {
|
||||
if (legacy_model_.loadUrdf(path)) return true;
|
||||
if (error) *error = "failed to load URDF: " + path;
|
||||
return false;
|
||||
}
|
||||
bool extractChain(const std::string& base, const std::string& tip,
|
||||
ChainInfo& out, std::string* error = nullptr) const {
|
||||
return extractChain(legacy_model_, base, tip, out, error);
|
||||
}
|
||||
const pinocchio::Model& model() const { return legacy_model_.kinematics(); }
|
||||
bool loaded() const { return legacy_model_.hasKinematics(); }
|
||||
private:
|
||||
pinocchio::Model model_;
|
||||
bool loaded_{false};
|
||||
RobotModel legacy_model_;
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
@ -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 <algorithm>
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
@ -16,59 +17,59 @@ IKSolver::IKSolver(const std::string& urdf_path,
|
||||
}
|
||||
}
|
||||
|
||||
IKSolver::IKSolver(std::shared_ptr<const UrdfParser> 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<UrdfParser>();
|
||||
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<const UrdfParser>& 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<std::string> names;
|
||||
std::vector<JointLimit> 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<std::string>& 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
|
||||
|
||||
@ -3,37 +3,23 @@
|
||||
#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <pinocchio/parsers/urdf.hpp>
|
||||
#include <pinocchio/multibody/model.hpp>
|
||||
|
||||
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;
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
#include <Eigen/Core>
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
@ -39,9 +40,9 @@ public:
|
||||
const std::string& tcp_frame_name = std::string());
|
||||
|
||||
/**
|
||||
* @brief 按外部 URDF 解析器构造。
|
||||
* @brief 按已加载的机器人模型构造。
|
||||
*/
|
||||
PinocchioIKBase(std::shared_ptr<const UrdfParser> 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<double>& q_chain,
|
||||
const std::vector<double>& qdot_chain,
|
||||
@ -114,12 +115,27 @@ public:
|
||||
std::vector<double>& qdot_out,
|
||||
double qdot_abs_max = std::numeric_limits<double>::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<double, 6, 1>&,
|
||||
const std::vector<double>&,
|
||||
std::vector<double>& qdot_out,
|
||||
const Eigen::VectorXd&,
|
||||
const Eigen::VectorXd&,
|
||||
double = std::numeric_limits<double>::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<pinocchio::Data> data_;
|
||||
// Feedback and online planning reuse a separate workspace, serialized here.
|
||||
// Never share mutable IK data_ with concurrent read-only queries.
|
||||
std::unique_ptr<pinocchio::Data> 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};
|
||||
|
||||
@ -45,11 +45,31 @@ public:
|
||||
std::vector<double>& qdot_out,
|
||||
double qdot_abs_max = std::numeric_limits<double>::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<double, 6, 1>& target_twist_base,
|
||||
const std::vector<double>& q_chain,
|
||||
std::vector<double>& qdot_out,
|
||||
const Eigen::VectorXd& lower,
|
||||
const Eigen::VectorXd& upper,
|
||||
double qdot_abs_max = std::numeric_limits<double>::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<double, 6, 1>& 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);
|
||||
|
||||
@ -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<double>& 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<double,6,Eigen::Dynamic> J_full(6, model_.nv);
|
||||
pinocchio::computeFrameJacobian(model_, *data_, q_full,
|
||||
Eigen::Matrix<double,6,Eigen::Dynamic> 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<double,6,Eigen::Dynamic> J_world(6, model_.nv);
|
||||
pinocchio::computeFrameJacobian(model_, *data_, q_full,
|
||||
Eigen::Matrix<double,6,Eigen::Dynamic> J_world(6, model().nv);
|
||||
pinocchio::computeFrameJacobian(model(), *data_, q_full,
|
||||
ee_id,
|
||||
pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED,
|
||||
J_world);
|
||||
|
||||
@ -23,40 +23,33 @@ PinocchioIKBase::PinocchioIKBase(const std::string& urdf_path,
|
||||
, tcp_frame_name_(tcp_frame_name) {
|
||||
}
|
||||
|
||||
PinocchioIKBase::PinocchioIKBase(std::shared_ptr<const UrdfParser> 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<std::mutex> query_lock(query_mutex_);
|
||||
data_ = std::make_unique<pinocchio::Data>(model());
|
||||
query_data_ = std::make_unique<pinocchio::Data>(model());
|
||||
|
||||
model_ = urdf_parser_->model();
|
||||
data_ = std::make_unique<pinocchio::Data>(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<double>& joints,
|
||||
Eigen::VectorXd& q_full,
|
||||
const char* context) const {
|
||||
const int size = static_cast<int>(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<const Eigen::VectorXd>(joints.data(), model_.nq);
|
||||
q_full = pinocchio::neutral(model());
|
||||
if (size == model().nq) {
|
||||
q_full = Eigen::Map<const Eigen::VectorXd>(joints.data(), model().nq);
|
||||
} else {
|
||||
Eigen::Map<const Eigen::VectorXd> 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<double>& q_chain_std,
|
||||
@ -217,8 +214,8 @@ bool PinocchioIKBase::buildJacobianBaseAtQ(const std::vector<double>& q_chain_st
|
||||
const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee;
|
||||
base_R_ee = base_M_ee.rotation();
|
||||
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_world(6, model_.nv);
|
||||
pinocchio::computeFrameJacobian(model_, *data_, q_full,
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> 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<double>& 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<std::mutex> 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<const Eigen::VectorXd> 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<double, 6, Eigen::Dynamic> jacobian_world(6, model_.nv);
|
||||
pinocchio::computeFrameJacobian(model_, *data_, q_full,
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> 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<double>& q_chain,
|
||||
@ -363,13 +366,13 @@ bool PinocchioIKBase::computeTwistBaseAtQ(const std::vector<double>& 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;
|
||||
|
||||
@ -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<double, 6, 1>& 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<double, 6, 1> 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<double> &joints_angle,
|
||||
bool is_tcp) {
|
||||
@ -356,8 +412,8 @@ namespace cmvr {
|
||||
dx.tail<3>() *= w_posrot_;
|
||||
|
||||
// 6×nv Jacobian(LOCAL)
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> J_full(6, model_.nv);
|
||||
pinocchio::computeFrameJacobian(model_, *data_, q_full,
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> 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<double>& 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<double, 6, 1>& target_twist_base,
|
||||
const std::vector<double>& q_chain_std,
|
||||
std::vector<double>& 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<const VectorXd> 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<const VectorXd> 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<std::uint64_t> 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<double>::infinity())
|
||||
<< ", external_upper=" << (has_external_bounds ? external_upper[i] : std::numeric_limits<double>::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<double, 6, 1> 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());
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
|
||||
@ -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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::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<double>::infinity();
|
||||
EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale(
|
||||
jacobian, target, lower, upper, scale));
|
||||
lower[0] = -1.0;
|
||||
target[0] = std::numeric_limits<double>::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<double> 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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
target.head<3>() = -0.04 * rotation.col(1);
|
||||
std::vector<double> qdot;
|
||||
ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot));
|
||||
ASSERT_EQ(qdot.size(), q.size());
|
||||
const Eigen::Map<const Eigen::VectorXd> velocity(qdot.data(), qdot.size());
|
||||
const Eigen::Matrix<double, 6, 1> 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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
target[0] = 0.04;
|
||||
const std::vector<double> 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<double> qdot;
|
||||
ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper));
|
||||
const Eigen::Map<const Eigen::VectorXd> 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<double> q = {0.0, 1.57, 0.0, 1.0, 0.0, 0.0, 0.0};
|
||||
Eigen::Matrix<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
target[1] = 0.04;
|
||||
std::vector<double> 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<double> q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.56};
|
||||
const Eigen::Matrix<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
std::vector<double> qdot;
|
||||
ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot));
|
||||
EXPECT_LT(Eigen::Map<const Eigen::VectorXd>(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<const Eigen::VectorXd> 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<double, 6, 1> target = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
target[5] = previous_velocity;
|
||||
std::vector<double> 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<double> 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<double> q = {0.582722602717, 1.18224927602, 1.476371331,
|
||||
0.30800863072, -2.97894487049, 0.408292452313, -0.568806827985};
|
||||
Eigen::Matrix<double, 6, 1> 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<double> 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<const Eigen::VectorXd> 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<double> 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<double> 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
|
||||
|
||||
49
cmvr-es/algorithms/planner/CMakeLists.txt
Normal file
49
cmvr-es/algorithms/planner/CMakeLists.txt
Normal file
@ -0,0 +1,49 @@
|
||||
add_library(lgv_base_motion SHARED
|
||||
cartesian/s_curve/src/s_curve_planner.cpp)
|
||||
target_include_directories(lgv_base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(lgv_base_motion PUBLIC
|
||||
cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common)
|
||||
add_library(cmvr_es::lgv_base_motion ALIAS lgv_base_motion)
|
||||
install(TARGETS lgv_base_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_library(lgv_arm_motion SHARED
|
||||
cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp
|
||||
cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp)
|
||||
target_include_directories(lgv_arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(lgv_arm_motion PUBLIC
|
||||
cmvr_es::ik_solver cmvr_es::lgv_base_motion cmvr_es::curves)
|
||||
add_library(cmvr_es::lgv_arm_motion ALIAS lgv_arm_motion)
|
||||
add_library(cmvr_es::algorithms::lgv_arm_motion ALIAS lgv_arm_motion)
|
||||
install(TARGETS lgv_arm_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_library(joint_path_planner SHARED
|
||||
joint/ompl/src/rrt_connect.cpp)
|
||||
target_include_directories(joint_path_planner PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(joint_path_planner PUBLIC cmvr_es::proto PRIVATE ompl)
|
||||
add_library(cmvr_es::joint_path_planner ALIAS joint_path_planner)
|
||||
install(TARGETS joint_path_planner LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(s_curve_planner_reversal_test
|
||||
cartesian/s_curve/test/s_curve_planner_reversal_test.cpp)
|
||||
target_link_libraries(s_curve_planner_reversal_test PRIVATE
|
||||
cmvr_es::lgv_base_motion gtest gtest_main)
|
||||
|
||||
add_executable(lgv_pinocchio_speedl_limits_test
|
||||
cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp)
|
||||
target_compile_definitions(lgv_pinocchio_speedl_limits_test PRIVATE
|
||||
CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(lgv_pinocchio_speedl_limits_test PRIVATE
|
||||
cmvr_es::algorithms::lgv_arm_motion gtest gtest_main)
|
||||
|
||||
add_executable(rrt_connect_test
|
||||
joint/ompl/test/rrt_connect_test.cpp)
|
||||
target_link_libraries(rrt_connect_test PRIVATE
|
||||
cmvr_es::joint_path_planner ompl gtest pthread)
|
||||
|
||||
add_executable(rrt_connect_self_collision_test
|
||||
joint/ompl/test/rrt_connect_self_collision_test.cpp)
|
||||
target_compile_definitions(rrt_connect_self_collision_test PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(rrt_connect_self_collision_test PRIVATE
|
||||
cmvr_es::joint_path_planner cmvr_es::collision_checker
|
||||
ompl gtest pthread)
|
||||
@ -0,0 +1,64 @@
|
||||
#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H
|
||||
#define CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#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<CartesianTrajectoryPlanner> createMoveL(
|
||||
const config::MoveLConfig& move_l,
|
||||
const std::shared_ptr<cmvr::PinocchioIKBase>& solver)
|
||||
{
|
||||
if (!solver) {
|
||||
return nullptr;
|
||||
}
|
||||
switch (move_l.algorithm_case()) {
|
||||
case config::MoveLConfig::kPinocchioCartesianMotionPlanner: {
|
||||
auto planner = std::make_shared<PinocchioCartesianTrajectoryPlanner>(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<CartesianVelocityPlanner> createSpeedL(
|
||||
const config::SpeedLConfig& speed_l,
|
||||
const std::shared_ptr<cmvr::PinocchioIKBase>& solver,
|
||||
std::size_t dof)
|
||||
{
|
||||
if (!solver) {
|
||||
return nullptr;
|
||||
}
|
||||
switch (speed_l.algorithm_case()) {
|
||||
case config::SpeedLConfig::kPinocchioCartesianMotionPlanner: {
|
||||
auto planner = std::make_shared<PinocchioCartesianVelocityPlanner>(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
|
||||
@ -0,0 +1,41 @@
|
||||
#ifndef CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
#define CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
struct CartesianJointTrajectory {
|
||||
std::vector<std::vector<double>> position;
|
||||
std::vector<std::vector<double>> velocity;
|
||||
std::vector<double> 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<double>& q_start,
|
||||
const std::vector<double>& qd_max,
|
||||
double velocity,
|
||||
double acceleration,
|
||||
double jerk,
|
||||
FrameType frame,
|
||||
CartesianJointTrajectory& trajectory) = 0;
|
||||
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
@ -0,0 +1,62 @@
|
||||
#ifndef CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H
|
||||
#define CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
#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<double>& q, const std::vector<double>& 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<double>& q,
|
||||
const std::vector<double>& 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<double>&,
|
||||
const std::vector<double>&) {
|
||||
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
|
||||
@ -0,0 +1,63 @@
|
||||
#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
#define CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
|
||||
#include <Eigen/Core>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<cmvr::PinocchioIKBase> solver);
|
||||
|
||||
bool configureMoveL(const config::MoveLPlannerConfig& config) override;
|
||||
|
||||
bool planMoveL(const CartesianPose& target,
|
||||
const std::vector<double>& q_start,
|
||||
const std::vector<double>& 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<double, 6, 1>& desired_twist,
|
||||
const Eigen::Matrix<double, 6, 1>& achieved_twist,
|
||||
double path_position,
|
||||
std::string& stop_reason) const;
|
||||
|
||||
std::shared_ptr<cmvr::PinocchioIKBase> solver_{nullptr};
|
||||
config::MoveLPlannerConfig movel_config_{};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H
|
||||
@ -0,0 +1,100 @@
|
||||
#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H
|
||||
#define CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H
|
||||
|
||||
#include <Eigen/Core>
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<cmvr::PinocchioIKBase> solver);
|
||||
|
||||
bool configureSpeedL(const config::SpeedLPlannerConfig& config,
|
||||
std::size_t dof) override;
|
||||
|
||||
Result reset(const std::vector<double>& q, const std::vector<double>& qd) override;
|
||||
Result submit(const CartesianVelocity& target, const SpeedLOptions& options,
|
||||
FrameType frame) override;
|
||||
CartesianVelocityStep step(double dt, const std::vector<double>& q_measured,
|
||||
const std::vector<double>& qd_measured,
|
||||
double speed_scaling = 1.0) override;
|
||||
CartesianVelocityStep brakeStep(double dt, const std::vector<double>& q,
|
||||
const std::vector<double>& qd) override;
|
||||
void commitStep() override;
|
||||
|
||||
private:
|
||||
CartesianVelocityStep stepImpl_(double dt, const std::vector<double>& q,
|
||||
const std::vector<double>& qd, double speed_scaling);
|
||||
double adaptiveScale_(const Eigen::Matrix<double, 6, 1>& target_base,
|
||||
const Eigen::MatrixXd& jacobian, const std::vector<double>& q,
|
||||
const std::vector<double>& 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<double>& q_measured,
|
||||
const Eigen::VectorXd& qdot,
|
||||
double dt) const;
|
||||
bool validateSpeedLCartesianVelocityFeasibility_(
|
||||
const Eigen::Matrix<double, 6, 1>& desired_twist,
|
||||
const Eigen::Matrix<double, 6, 1>& 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<cmvr::PinocchioIKBase> solver_{nullptr};
|
||||
config::SpeedLPlannerConfig speedl_config_{};
|
||||
struct State {
|
||||
cmvr::LgvSCurvePlanner s_curve_planner_{};
|
||||
Eigen::VectorXd joint_acceleration_limits_;
|
||||
std::vector<double> prev_qdot_command_;
|
||||
Eigen::Matrix<double, 6, 1> speedl_command_twist_base_{Eigen::Matrix<double, 6, 1>::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<double, 6, 1> adaptive_original_target{Eigen::Matrix<double, 6, 1>::Zero()};
|
||||
Eigen::Matrix<double, 6, 1> adaptive_limited_target{Eigen::Matrix<double, 6, 1>::Zero()};
|
||||
Eigen::Matrix<double, 6, 1> adaptive_direction_base{Eigen::Matrix<double, 6, 1>::Zero()};
|
||||
Eigen::VectorXd adaptive_joint_direction;
|
||||
};
|
||||
State state_;
|
||||
std::optional<State> pending_;
|
||||
|
||||
bool speedl_configured_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H
|
||||
@ -0,0 +1,679 @@
|
||||
#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <Eigen/Geometry>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#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<double, std::milli>(end - start).count();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PinocchioCartesianTrajectoryPlanner::PinocchioCartesianTrajectoryPlanner(
|
||||
std::shared_ptr<cmvr::PinocchioIKBase> 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<double>& q_start,
|
||||
const std::vector<double>& 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<double>(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<int>(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<double>(q_start.size(), 0.0));
|
||||
trajectory.time.push_back(0.0);
|
||||
if (path_length <= 1e-9) {
|
||||
return true;
|
||||
}
|
||||
|
||||
cmvr::LgvSCurve curve(velocity, acceleration, jerk);
|
||||
const cmvr::LgvSCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0);
|
||||
if (profile.total_time <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
const auto reserve_count =
|
||||
static_cast<std::size_t>(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<double> q_std(q_start.size(), 0.0);
|
||||
std::vector<double> q_next_std(q_start.size(), 0.0);
|
||||
std::vector<double> 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<double>& dst) {
|
||||
dst.resize(static_cast<std::size_t>(src.size()));
|
||||
Eigen::Map<Eigen::VectorXd>(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<double, 6, 1> target_twist_base = Eigen::Matrix<double, 6, 1>::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<double>::infinity());
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Map<const Eigen::VectorXd> qdot(qdot_std.data(),
|
||||
static_cast<Eigen::Index>(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<std::size_t>(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<double, 6, 1> 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<std::string> 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<std::size_t>(i) < joint_names.size()
|
||||
? joint_names[static_cast<std::size_t>(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<double, 6, 1>& desired_twist,
|
||||
const Eigen::Matrix<double, 6, 1>& 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
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,136 @@
|
||||
#pragma once
|
||||
|
||||
#include <Eigen/Core>
|
||||
#include <array>
|
||||
#include <utility>
|
||||
#include "curves/s_curve/include/s_curve.h"
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
enum class LgvCartesianFrame
|
||||
{
|
||||
Base = 0,
|
||||
Tool = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 基于 LgvSCurve 的六维末端在线速度规划器。
|
||||
*
|
||||
* initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。
|
||||
* 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。
|
||||
* 非连续模式与角速度近反向时,先停稳再反向。
|
||||
* 传入零目标平滑停止;相同目标会继续当前曲线,不会每拍重规划。
|
||||
* 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。
|
||||
* 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。
|
||||
*/
|
||||
class LgvSCurvePlanner
|
||||
{
|
||||
public:
|
||||
using Twist = Eigen::Matrix<double, 6, 1>;
|
||||
|
||||
void setLinearConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
void setAngularConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
void setLinearTargetReplanThreshold(double threshold);
|
||||
void setAngularTargetReplanThreshold(double threshold);
|
||||
|
||||
// 连续过零保留加速度;关闭后近反向等待停稳。
|
||||
void setContinuousLinearReversal(bool enabled);
|
||||
bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; }
|
||||
|
||||
// 清除旧曲线,用 Base 系初始速度开始规划。
|
||||
void initialize(const Twist& initial_twist = Twist::Zero());
|
||||
|
||||
// 每周期调用一次。Tool 目标按当拍 base_R_tool 转到 Base 系。
|
||||
Twist plan(const Twist& target_twist, LgvCartesianFrame frame,
|
||||
double dt, const Eigen::Matrix3d& base_R_tool);
|
||||
|
||||
const Twist& getTwistBase() const { return twist_base_; }
|
||||
const Twist& getAccelerationBase() const { return acceleration_base_; }
|
||||
const Twist& getJerkBase() const { return jerk_base_; }
|
||||
bool isMoving() const;
|
||||
|
||||
private:
|
||||
static constexpr double EPSILON = 1e-12;
|
||||
static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999;
|
||||
|
||||
// 保存一维速度曲线的运行状态;数学计算由 LgvSCurve 完成。
|
||||
struct VelocityState {
|
||||
struct Sample {
|
||||
double velocity{0.0};
|
||||
double acceleration{0.0};
|
||||
double target_velocity{0.0};
|
||||
double elapsed_time{0.0};
|
||||
bool has_active_profile{false};
|
||||
};
|
||||
|
||||
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
|
||||
void setTargetReplanThreshold(double threshold);
|
||||
void initialize(double velocity = 0.0, double acceleration = 0.0);
|
||||
void setTargetVelocity(double target_velocity);
|
||||
double update(double dt);
|
||||
|
||||
double getVelocity() const { return state_.velocity; }
|
||||
double getAcceleration() const { return state_.acceleration; }
|
||||
double replanThreshold() const { return target_replan_threshold_; }
|
||||
std::array<double, 3> limits() const;
|
||||
bool isSettled() const;
|
||||
bool isMoving() const;
|
||||
|
||||
private:
|
||||
void replan();
|
||||
|
||||
LgvSCurve curve_{1.0, 1.0, 5.0};
|
||||
Sample state_;
|
||||
LgvSCurveVelocityProfile active_profile_;
|
||||
double target_replan_threshold_{1e-9};
|
||||
static constexpr double VELOCITY_THRESHOLD = 1e-6;
|
||||
};
|
||||
|
||||
// Cubic Bezier velocity: endpoint accelerations are a0 and zero.
|
||||
// Derivative control-point norms certify complete v/a/j bounds.
|
||||
struct DirectionProfile {
|
||||
std::array<Eigen::Vector3d, 4> 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<Eigen::Vector3d, Eigen::Vector3d> sample(double time) const;
|
||||
bool fits(const std::array<double, 3>& 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<double, 3>& 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
|
||||
@ -0,0 +1,47 @@
|
||||
#ifndef CMVR_ES_S_CURVE_PLANNER_CONFIG_H
|
||||
#define CMVR_ES_S_CURVE_PLANNER_CONFIG_H
|
||||
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h"
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "common/config/config_files.h"
|
||||
|
||||
namespace cmvr::device::cartesian_motion {
|
||||
|
||||
inline void configureSCurvePlannerFromSpeedLConfig(
|
||||
cmvr::LgvSCurvePlanner& planner,
|
||||
const config::SpeedLPlannerConfig& config)
|
||||
{
|
||||
using cmvr::common::config::positiveOr;
|
||||
|
||||
// Zero retains the protobuf default; reject bad values before changing the planner.
|
||||
for (const double value : {config.linear_velocity_max(), config.linear_acceleration_max(),
|
||||
config.linear_jerk_max(), config.angular_velocity_max(),
|
||||
config.angular_acceleration_max(), config.angular_jerk_max(),
|
||||
config.linear_target_replan_threshold(),
|
||||
config.angular_target_replan_threshold()}) {
|
||||
if (!std::isfinite(value) || value < 0.0) {
|
||||
throw std::invalid_argument("speedL limits and thresholds must be finite and non-negative");
|
||||
}
|
||||
}
|
||||
|
||||
planner.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
|
||||
positiveOr(config.linear_acceleration_max(), 5.0),
|
||||
positiveOr(config.linear_jerk_max(), 10.0));
|
||||
planner.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
|
||||
positiveOr(config.angular_acceleration_max(), 5.0),
|
||||
positiveOr(config.angular_jerk_max(), 12.0));
|
||||
planner.setLinearTargetReplanThreshold(
|
||||
positiveOr(config.linear_target_replan_threshold(), 1e-4));
|
||||
planner.setAngularTargetReplanThreshold(
|
||||
positiveOr(config.angular_target_replan_threshold(), 1e-4));
|
||||
planner.setContinuousLinearReversal(!config.has_continuous_linear_reversal() ||
|
||||
config.continuous_linear_reversal());
|
||||
planner.initialize(Eigen::Matrix<double, 6, 1>::Zero());
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::cartesian_motion
|
||||
|
||||
#endif // CMVR_ES_S_CURVE_PLANNER_CONFIG_H
|
||||
@ -0,0 +1,420 @@
|
||||
#include "../include/s_curve_planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
namespace {
|
||||
void validateLimits(double velocity, double acceleration, double jerk)
|
||||
{
|
||||
// LgvSCurve's solver treats acceleration/jerk <= 1e-9 as degenerate.
|
||||
if (!std::isfinite(velocity) || velocity <= 1e-9 ||
|
||||
!std::isfinite(acceleration) || acceleration <= 1e-9 ||
|
||||
!std::isfinite(jerk) || jerk <= 1e-9) {
|
||||
throw std::invalid_argument("S-curve limits must be finite and greater than 1e-9");
|
||||
}
|
||||
}
|
||||
|
||||
bool withinLimit(double value, double limit)
|
||||
{
|
||||
return std::isfinite(value) && value <= limit * (1.0 + 1e-10);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::array<double, 3> LgvSCurvePlanner::VelocityState::limits() const
|
||||
{
|
||||
std::array<double, 3> result;
|
||||
curve_.getConstraints(result[0], result[1], result[2]);
|
||||
return result;
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::VelocityState::setConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
validateLimits(max_velocity, max_acceleration, max_jerk);
|
||||
if (!withinLimit(std::abs(state_.velocity), max_velocity) ||
|
||||
!withinLimit(std::abs(state_.acceleration), max_acceleration)) {
|
||||
throw std::invalid_argument("S-curve limits exclude the current velocity or acceleration");
|
||||
}
|
||||
if (limits() == std::array<double, 3>{max_velocity, max_acceleration, max_jerk}) return;
|
||||
|
||||
auto staged = *this;
|
||||
staged.curve_.setConstraints(max_velocity, max_acceleration, max_jerk);
|
||||
staged.state_.target_velocity =
|
||||
std::clamp(state_.target_velocity, -max_velocity, max_velocity);
|
||||
if (state_.has_active_profile || state_.acceleration != 0.0) staged.replan();
|
||||
*this = std::move(staged);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold)
|
||||
{
|
||||
if (!std::isfinite(threshold) || threshold < 0.0) {
|
||||
throw std::invalid_argument("S-curve replan threshold must be nonnegative and finite");
|
||||
}
|
||||
target_replan_threshold_ = threshold;
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::VelocityState::initialize(double velocity, double acceleration)
|
||||
{
|
||||
const auto bounds = limits();
|
||||
if (!withinLimit(std::abs(velocity), bounds[0]) ||
|
||||
!withinLimit(std::abs(acceleration), bounds[1])) {
|
||||
throw std::invalid_argument("S-curve initial velocity or acceleration exceeds limits");
|
||||
}
|
||||
state_ = Sample{};
|
||||
state_.velocity = velocity;
|
||||
state_.acceleration = acceleration;
|
||||
state_.target_velocity = velocity;
|
||||
active_profile_ = LgvSCurveVelocityProfile();
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::VelocityState::setTargetVelocity(double target_velocity)
|
||||
{
|
||||
const double velocity_limit = limits()[0];
|
||||
const double new_target = std::clamp(target_velocity, -velocity_limit, velocity_limit);
|
||||
const bool same_target =
|
||||
std::abs(new_target - state_.target_velocity) <= target_replan_threshold_;
|
||||
if (same_target && (state_.has_active_profile ||
|
||||
(std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0))) return;
|
||||
|
||||
state_.target_velocity = new_target;
|
||||
replan();
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::VelocityState::replan()
|
||||
{
|
||||
const auto candidate = curve_.calculateVelocityProfile(
|
||||
state_.velocity, state_.target_velocity, state_.acceleration);
|
||||
const double values[] = {candidate.t1, candidate.t2, candidate.t3,
|
||||
candidate.total_time, candidate.j1, candidate.j2, candidate.j3,
|
||||
candidate.v0, candidate.a0, candidate.vf};
|
||||
const bool finite = std::all_of(std::begin(values), std::end(values),
|
||||
[](double value) { return std::isfinite(value); });
|
||||
if (!finite || !candidate.valid || candidate.total_time <= 0.0 ||
|
||||
candidate.t1 < 0.0 || candidate.t2 < 0.0 || candidate.t3 < 0.0) {
|
||||
if (finite && std::abs(state_.velocity - state_.target_velocity) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0) {
|
||||
state_.has_active_profile = false;
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error("S-curve could not generate a finite feasible velocity profile");
|
||||
}
|
||||
// The mathematical solver must not silently clamp the starting state.
|
||||
if (std::abs(candidate.v0 - state_.velocity) > 1e-12 ||
|
||||
std::abs(candidate.a0 - state_.acceleration) > 1e-12) {
|
||||
throw std::runtime_error("S-curve profile changed its initial state");
|
||||
}
|
||||
active_profile_ = candidate;
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = true;
|
||||
}
|
||||
|
||||
double LgvSCurvePlanner::VelocityState::update(double dt)
|
||||
{
|
||||
if (!state_.has_active_profile) {
|
||||
if (state_.acceleration != 0.0 ||
|
||||
std::abs(state_.velocity - state_.target_velocity) > VELOCITY_THRESHOLD) {
|
||||
throw std::runtime_error("S-curve has no active profile for a moving transition");
|
||||
}
|
||||
return state_.velocity;
|
||||
}
|
||||
state_.elapsed_time = std::min(state_.elapsed_time + dt, active_profile_.total_time);
|
||||
if (state_.elapsed_time >= active_profile_.total_time) {
|
||||
state_.velocity = active_profile_.vf;
|
||||
state_.acceleration = 0.0;
|
||||
state_.has_active_profile = false;
|
||||
} else {
|
||||
state_.velocity = curve_.getVelocityAtTime(active_profile_, state_.elapsed_time);
|
||||
state_.acceleration = curve_.getAccelerationAtTime(active_profile_, state_.elapsed_time);
|
||||
}
|
||||
if (!std::isfinite(state_.velocity) || !std::isfinite(state_.acceleration)) {
|
||||
throw std::runtime_error("S-curve produced a non-finite state");
|
||||
}
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
bool LgvSCurvePlanner::VelocityState::isSettled() const
|
||||
{
|
||||
return !state_.has_active_profile &&
|
||||
std::abs(state_.velocity) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0;
|
||||
}
|
||||
|
||||
bool LgvSCurvePlanner::VelocityState::isMoving() const
|
||||
{
|
||||
return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD;
|
||||
}
|
||||
|
||||
std::pair<Eigen::Vector3d, Eigen::Vector3d>
|
||||
LgvSCurvePlanner::DirectionProfile::sample(double time) const
|
||||
{
|
||||
const double u = std::clamp(time / duration, 0.0, 1.0);
|
||||
const double r = 1.0 - u;
|
||||
const Eigen::Vector3d velocity = r*r*r*control[0] + 3*r*r*u*control[1] +
|
||||
3*r*u*u*control[2] + u*u*u*control[3];
|
||||
const Eigen::Vector3d acceleration = (3.0 / duration) *
|
||||
(r*r*(control[1]-control[0]) + 2*r*u*(control[2]-control[1]) +
|
||||
u*u*(control[3]-control[2]));
|
||||
return {velocity, acceleration};
|
||||
}
|
||||
|
||||
bool LgvSCurvePlanner::DirectionProfile::fits(const std::array<double, 3>& bounds) const
|
||||
{
|
||||
if (!std::isfinite(duration) || duration <= 0.0) return false;
|
||||
std::array<Eigen::Vector3d, 3> acceleration;
|
||||
for (std::size_t i = 0; i < control.size(); ++i) {
|
||||
if (!withinLimit(control[i].norm(), bounds[0])) return false;
|
||||
if (i < acceleration.size()) {
|
||||
acceleration[i] = (3.0 / duration) * (control[i+1] - control[i]);
|
||||
if (!withinLimit(acceleration[i].norm(), bounds[1])) return false;
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < 2; ++i) {
|
||||
if (!withinLimit(((2.0 / duration) * (acceleration[i+1] - acceleration[i])).norm(),
|
||||
bounds[2])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LgvSCurvePlanner::DirectionProfile LgvSCurvePlanner::DirectionProfile::remaining() const
|
||||
{
|
||||
auto result = *this;
|
||||
auto work = control;
|
||||
const double u = std::clamp(elapsed / duration, 0.0, 1.0);
|
||||
for (std::size_t level = 1; level < control.size(); ++level) {
|
||||
for (std::size_t i = 0; i < control.size() - level; ++i) {
|
||||
work[i] = (1.0 - u) * work[i] + u * work[i+1];
|
||||
}
|
||||
result.control[control.size()-level-1] = work[control.size()-level-1];
|
||||
}
|
||||
result.duration -= elapsed;
|
||||
result.elapsed = 0.0;
|
||||
return result;
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile,
|
||||
double velocity, double acceleration, double jerk)
|
||||
{
|
||||
validateLimits(velocity, acceleration, jerk);
|
||||
if (scalar.limits() == std::array<double, 3>{velocity, acceleration, jerk}) return;
|
||||
if (profile.active && !profile.remaining().fits({velocity, acceleration, jerk})) {
|
||||
throw std::invalid_argument("S-curve limits exclude the remaining direction transition");
|
||||
}
|
||||
// While a vector curve is active the scalar state is dormant at zero.
|
||||
scalar.setConstraints(velocity, acceleration, jerk);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk)
|
||||
{
|
||||
setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk)
|
||||
{
|
||||
setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setLinearTargetReplanThreshold(double threshold)
|
||||
{
|
||||
linear_velocity_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setAngularTargetReplanThreshold(double threshold)
|
||||
{
|
||||
angular_velocity_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::setContinuousLinearReversal(bool enabled)
|
||||
{
|
||||
if (continuous_linear_reversal_ == enabled) return;
|
||||
if (!enabled && !linear_direction_profile_.active) {
|
||||
const double velocity = linear_velocity_.getVelocity();
|
||||
const double acceleration = linear_velocity_.getAcceleration();
|
||||
if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) {
|
||||
linear_velocity_.initialize(-velocity, -acceleration);
|
||||
current_linear_dir_base_ = -current_linear_dir_base_;
|
||||
}
|
||||
}
|
||||
if (enabled) linear_direction_profile_.stopping_for_reversal = false;
|
||||
continuous_linear_reversal_ = enabled;
|
||||
}
|
||||
|
||||
void LgvSCurvePlanner::initialize(const Twist& initial_twist)
|
||||
{
|
||||
const Eigen::Vector3d v0 = initial_twist.head<3>();
|
||||
const Eigen::Vector3d w0 = initial_twist.tail<3>();
|
||||
const double v0_norm = v0.norm();
|
||||
const double w0_norm = w0.norm();
|
||||
if (!initial_twist.allFinite() || !std::isfinite(v0_norm) || !std::isfinite(w0_norm)) {
|
||||
throw std::invalid_argument("S-curve initial twist must be finite");
|
||||
}
|
||||
auto staged = *this;
|
||||
staged.linear_velocity_.initialize(v0_norm, 0.0);
|
||||
staged.angular_velocity_.initialize(w0_norm, 0.0);
|
||||
staged.linear_direction_profile_ = DirectionProfile{};
|
||||
staged.angular_direction_profile_ = DirectionProfile{};
|
||||
staged.twist_base_ = initial_twist;
|
||||
staged.acceleration_base_.setZero();
|
||||
staged.jerk_base_.setZero();
|
||||
staged.previous_period_ = 0.0;
|
||||
staged.current_linear_dir_base_.setZero();
|
||||
staged.current_angular_dir_base_.setZero();
|
||||
if (v0_norm > EPSILON) staged.current_linear_dir_base_ = v0 / v0_norm;
|
||||
if (w0_norm > EPSILON) staged.current_angular_dir_base_ = w0 / w0_norm;
|
||||
*this = std::move(staged);
|
||||
}
|
||||
|
||||
bool LgvSCurvePlanner::planDirection(const Eigen::Vector3d& velocity,
|
||||
const Eigen::Vector3d& acceleration,
|
||||
const Eigen::Vector3d& target, double dt,
|
||||
const std::array<double, 3>& bounds,
|
||||
DirectionProfile& profile)
|
||||
{
|
||||
const double delta = (target - velocity).norm();
|
||||
const double a = acceleration.norm();
|
||||
// Necessary lower bounds; feasibility is not monotone in duration because
|
||||
// P1 = v0 + T*a0/3 can leave the velocity ball when T grows.
|
||||
const double a_over_j = a / bounds[2];
|
||||
const double delta_over_j = 6.0 * (delta / bounds[2]);
|
||||
const double denominator = std::hypot(2.0 * a_over_j, std::sqrt(delta_over_j)) +
|
||||
2.0 * a_over_j;
|
||||
const double jerk_duration = denominator > 0.0 ? delta_over_j / denominator : 0.0;
|
||||
double duration = std::max({1e-9, std::min(dt, 1e-6), a_over_j, jerk_duration,
|
||||
3.0 * delta / (bounds[1] + a)});
|
||||
for (int attempt = 0; attempt < 50 && std::isfinite(duration); ++attempt) {
|
||||
DirectionProfile candidate;
|
||||
candidate.control = {velocity, velocity + (duration / 3.0) * acceleration,
|
||||
target, target};
|
||||
candidate.duration = duration;
|
||||
candidate.active = true;
|
||||
candidate.stopping_for_reversal = profile.stopping_for_reversal;
|
||||
if (candidate.fits(bounds)) {
|
||||
profile = std::move(candidate);
|
||||
return true;
|
||||
}
|
||||
duration *= 1.18;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Vector3d LgvSCurvePlanner::planVelocity(VelocityState& scalar,
|
||||
DirectionProfile& profile,
|
||||
Eigen::Vector3d& direction,
|
||||
const Eigen::Vector3d& target, double dt,
|
||||
bool continuous_reversal)
|
||||
{
|
||||
const auto bounds = scalar.limits();
|
||||
Eigen::Vector3d desired = target;
|
||||
const double target_norm = target.norm();
|
||||
if (target_norm > bounds[0]) desired *= bounds[0] / target_norm;
|
||||
|
||||
Eigen::Vector3d velocity = direction * scalar.getVelocity();
|
||||
Eigen::Vector3d acceleration = direction * scalar.getAcceleration();
|
||||
if (profile.active) {
|
||||
const auto state = profile.sample(profile.elapsed);
|
||||
velocity = state.first;
|
||||
acceleration = state.second;
|
||||
if (!continuous_reversal && velocity.norm() > EPSILON && desired.norm() > EPSILON &&
|
||||
velocity.normalized().dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD) {
|
||||
profile.stopping_for_reversal = true;
|
||||
}
|
||||
}
|
||||
if (profile.stopping_for_reversal) desired.setZero();
|
||||
|
||||
if (!profile.active) {
|
||||
if (velocity.isZero(0.0) && acceleration.isZero(0.0)) {
|
||||
if (desired.norm() > EPSILON) direction = desired.normalized();
|
||||
scalar.setTargetVelocity(desired.norm());
|
||||
return direction * scalar.update(dt);
|
||||
}
|
||||
const double signed_target = direction.dot(desired);
|
||||
const bool collinear = (desired - signed_target * direction).norm() <=
|
||||
1e-12 * desired.norm();
|
||||
const bool reverse = desired.norm() > EPSILON &&
|
||||
direction.dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD;
|
||||
if (desired.norm() <= EPSILON || (!continuous_reversal && reverse) ||
|
||||
(collinear && (continuous_reversal || signed_target >= 0.0))) {
|
||||
scalar.setTargetVelocity((!continuous_reversal && reverse) ? 0.0 : signed_target);
|
||||
const auto result = direction * scalar.update(dt);
|
||||
if (profile.stopping_for_reversal && scalar.isSettled()) {
|
||||
profile.stopping_for_reversal = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (!profile.active ||
|
||||
(desired - profile.control.back()).norm() > scalar.replanThreshold()) {
|
||||
if (planDirection(velocity, acceleration, desired, dt, bounds, profile)) {
|
||||
scalar.initialize();
|
||||
}
|
||||
}
|
||||
// A rejected candidate leaves the certified old curve running. In particular,
|
||||
// preserve its acceleration instead of holding one velocity sample.
|
||||
if (!profile.active) return direction * scalar.update(dt);
|
||||
profile.elapsed = std::min(profile.elapsed + dt, profile.duration);
|
||||
velocity = profile.sample(profile.elapsed).first;
|
||||
if (profile.elapsed >= profile.duration) {
|
||||
profile.active = false;
|
||||
const double speed = velocity.norm();
|
||||
scalar.initialize(speed, 0.0);
|
||||
if (speed > EPSILON) direction = velocity / speed;
|
||||
if (speed <= EPSILON) profile.stopping_for_reversal = false;
|
||||
}
|
||||
return velocity;
|
||||
}
|
||||
|
||||
LgvSCurvePlanner::Twist
|
||||
LgvSCurvePlanner::plan(const Twist& target_twist, LgvCartesianFrame frame,
|
||||
double dt, const Eigen::Matrix3d& base_R_tool)
|
||||
{
|
||||
// Smaller periods cannot reliably support command differences in double precision.
|
||||
if (!std::isfinite(dt) || dt < 1e-9) {
|
||||
throw std::invalid_argument("S-curve period must be finite and at least 1e-9 seconds");
|
||||
}
|
||||
if ((frame != LgvCartesianFrame::Base && frame != LgvCartesianFrame::Tool) ||
|
||||
!target_twist.allFinite() ||
|
||||
(frame == LgvCartesianFrame::Tool && !base_R_tool.allFinite())) {
|
||||
throw std::invalid_argument("invalid S-curve target, frame or tool rotation");
|
||||
}
|
||||
Twist target_base = target_twist;
|
||||
if (frame == LgvCartesianFrame::Tool) {
|
||||
target_base.head<3>() = base_R_tool * target_twist.head<3>();
|
||||
target_base.tail<3>() = base_R_tool * target_twist.tail<3>();
|
||||
}
|
||||
if (!target_base.allFinite() || !std::isfinite(target_base.head<3>().norm()) ||
|
||||
!std::isfinite(target_base.tail<3>().norm())) {
|
||||
throw std::invalid_argument("S-curve target magnitude must be finite");
|
||||
}
|
||||
auto staged = *this;
|
||||
staged.twist_base_.head<3>() = planVelocity(staged.linear_velocity_,
|
||||
staged.linear_direction_profile_, staged.current_linear_dir_base_,
|
||||
target_base.head<3>(), dt, continuous_linear_reversal_);
|
||||
staged.twist_base_.tail<3>() = planVelocity(staged.angular_velocity_,
|
||||
staged.angular_direction_profile_, staged.current_angular_dir_base_,
|
||||
target_base.tail<3>(), dt, false);
|
||||
// Keep the public diagnostics based on actual output commands.
|
||||
staged.acceleration_base_ = (staged.twist_base_ - twist_base_) / dt;
|
||||
// Acceleration samples are averages over intervals, located at their centers.
|
||||
staged.jerk_base_ = (staged.acceleration_base_ - acceleration_base_) /
|
||||
(0.5 * previous_period_ + 0.5 * dt);
|
||||
staged.previous_period_ = dt;
|
||||
if (!staged.twist_base_.allFinite() || !staged.acceleration_base_.allFinite() ||
|
||||
!staged.jerk_base_.allFinite()) {
|
||||
throw std::runtime_error("S-curve produced a non-finite command");
|
||||
}
|
||||
*this = std::move(staged);
|
||||
return twist_base_;
|
||||
}
|
||||
|
||||
bool LgvSCurvePlanner::isMoving() const
|
||||
{
|
||||
return linear_direction_profile_.active || angular_direction_profile_.active ||
|
||||
linear_velocity_.isMoving() || angular_velocity_.isMoving();
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -0,0 +1,320 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
using Twist = LgvSCurvePlanner::Twist;
|
||||
constexpr double dt = .001;
|
||||
Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; }
|
||||
struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; };
|
||||
Motion reverse(bool continuous, int approach_ticks) {
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(.55, 5, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
planner.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero());
|
||||
for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
planner.setLinearConstraints(.55, 3, 10);
|
||||
Motion result;
|
||||
double position = 0;
|
||||
for (int i = 1; i <= 1500; ++i) {
|
||||
const auto v = planner.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
position += v.y() * dt;
|
||||
result.peak = std::max(result.peak, position);
|
||||
if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt;
|
||||
if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt;
|
||||
if (continuous) {
|
||||
EXPECT_LE(planner.getAccelerationBase().norm(), 3.0 + 1e-7);
|
||||
EXPECT_LE(planner.getJerkBase().norm(), 10.0 + 1e-6);
|
||||
EXPECT_NEAR(v.x(), 0, 1e-12);
|
||||
EXPECT_NEAR(v.z(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
EXPECT_NEAR(planner.getTwistBase().y(), -.08, 1e-9);
|
||||
return result;
|
||||
}
|
||||
TEST(LgvSCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) {
|
||||
for (const int ticks : {0, 80, 120}) {
|
||||
SCOPED_TRACE(ticks);
|
||||
const auto legacy = reverse(false, ticks);
|
||||
const auto continuous = reverse(true, ticks);
|
||||
EXPECT_GT(continuous.reverse_time, 0);
|
||||
EXPECT_LT(continuous.reverse_time, legacy.reverse_time);
|
||||
EXPECT_LT(continuous.return_time, legacy.return_time);
|
||||
EXPECT_LT(continuous.peak, legacy.peak);
|
||||
}
|
||||
}
|
||||
TEST(LgvSCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 1, 4);
|
||||
planner.initialize(y(.02));
|
||||
for (int i = 0; i < 100; ++i) planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR(planner.getTwistBase().y(), 0, 1e-12);
|
||||
EXPECT_TRUE(planner.isMoving());
|
||||
EXPECT_LT(planner.getAccelerationBase().y(), -.39);
|
||||
EXPECT_LT(planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003);
|
||||
}
|
||||
TEST(LgvSCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) {
|
||||
for (double v : {.08, -.08}) {
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
planner.initialize(y(v));
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
EXPECT_GE(planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
|
||||
}
|
||||
EXPECT_FALSE(planner.isMoving());
|
||||
EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) {
|
||||
for (bool continuous : {true, false}) {
|
||||
for (int offset : {0, 3}) {
|
||||
for (bool accelerating : {false, true}) {
|
||||
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
|
||||
<< " angular=" << (offset == 3) << " accelerating=" << accelerating);
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
planner.setAngularConstraints(1, 3, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
Twist initial = Twist::Zero(), target = Twist::Zero();
|
||||
initial[offset + 1] = .08;
|
||||
target[offset] = .08;
|
||||
if (accelerating) {
|
||||
planner.initialize();
|
||||
planner.plan(initial, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
ASSERT_LT(planner.getTwistBase().norm(), 1e-3);
|
||||
ASSERT_GT(planner.getAccelerationBase().norm(), 1e-3);
|
||||
} else {
|
||||
planner.initialize(initial);
|
||||
}
|
||||
double max_acceleration = 0, max_jerk = 0;
|
||||
Twist previous = planner.getTwistBase();
|
||||
Twist previous_acceleration = planner.getAccelerationBase();
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const auto v = planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const Twist acceleration = (v - previous) / dt;
|
||||
const Twist jerk = (acceleration - previous_acceleration) / dt;
|
||||
EXPECT_LE(acceleration.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(jerk.norm(), 10 + 1e-5);
|
||||
previous = v;
|
||||
previous_acceleration = acceleration;
|
||||
max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm());
|
||||
max_jerk = std::max(max_jerk, planner.getJerkBase().norm());
|
||||
}
|
||||
EXPECT_LE(max_acceleration, 3 + 1e-6);
|
||||
EXPECT_LE(max_jerk, 10 + 1e-6);
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
|
||||
// Same-axis magnitude planning must keep moving when the target
|
||||
// has the same direction, including legacy linear streaming.
|
||||
target *= 1.5;
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
EXPECT_GE(planner.plan(target, LgvCartesianFrame::Base, dt,
|
||||
Eigen::Matrix3d::Identity())[offset], .08 - 1e-9);
|
||||
}
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
|
||||
if (offset == 3) {
|
||||
target = -target;
|
||||
max_acceleration = max_jerk = 0;
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm());
|
||||
max_jerk = std::max(max_jerk, planner.getJerkBase().norm());
|
||||
}
|
||||
EXPECT_LE(max_acceleration, 3 + 1e-6);
|
||||
EXPECT_LE(max_jerk, 10 + 1e-6);
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) {
|
||||
for (bool continuous : {true, false}) {
|
||||
for (int offset : {0, 3}) {
|
||||
for (double max_velocity : {.08, 1.}) {
|
||||
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
|
||||
<< " angular=" << (offset == 3) << " vmax=" << max_velocity);
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(max_velocity, 3, 10);
|
||||
planner.setAngularConstraints(max_velocity, 3, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
Twist target = Twist::Zero();
|
||||
target[offset] = .08;
|
||||
planner.initialize(target);
|
||||
Twist previous = target, previous_acceleration = Twist::Zero();
|
||||
double min_speed = .08;
|
||||
for (int i = 0; i < 3000; ++i) {
|
||||
// First reproduce the .01-rad step, then keep rotating the Tool.
|
||||
const double angle = .01 + .2 * i * dt;
|
||||
Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity();
|
||||
rotation(0, 0) = rotation(1, 1) = std::cos(angle);
|
||||
rotation(0, 1) = -std::sin(angle);
|
||||
rotation(1, 0) = std::sin(angle);
|
||||
const Twist v = planner.plan(target, LgvCartesianFrame::Tool, dt, rotation);
|
||||
const Twist a = (v - previous) / dt;
|
||||
const Twist j = (a - previous_acceleration) / dt;
|
||||
EXPECT_LE(v.norm(), max_velocity + 1e-9);
|
||||
EXPECT_LE(a.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(j.norm(), 10 + 1e-5);
|
||||
min_speed = std::min(min_speed, v.norm());
|
||||
previous = v;
|
||||
previous_acceleration = a;
|
||||
}
|
||||
EXPECT_GT(min_speed, .072);
|
||||
for (int i = 0; i < 1500; ++i) {
|
||||
const Twist v = planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt,
|
||||
Eigen::Matrix3d::Identity());
|
||||
const Twist a = (v - previous) / dt;
|
||||
EXPECT_LE(a.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(((a - previous_acceleration) / dt).norm(), 10 + 1e-5);
|
||||
previous = v;
|
||||
previous_acceleration = a;
|
||||
}
|
||||
EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-10);
|
||||
EXPECT_FALSE(planner.isMoving());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
|
||||
for (const int reverse_ticks : {150, 250, 500}) {
|
||||
SCOPED_TRACE(reverse_ticks);
|
||||
LgvSCurvePlanner reference;
|
||||
reference.setLinearConstraints(1, 3, 10);
|
||||
reference.initialize(y(.08));
|
||||
for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
ASSERT_LT(reference.getTwistBase().y(), 0);
|
||||
auto streaming = reference;
|
||||
streaming.setContinuousLinearReversal(false);
|
||||
EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12);
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
const auto expected = reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const auto actual = streaming.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR((actual - expected).norm(), 0, 1e-9);
|
||||
EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) {
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, .01);
|
||||
planner.initialize(y(.08));
|
||||
Twist target = Twist::Zero();
|
||||
target.x() = .08 * std::sin(1e-4);
|
||||
target.y() = .08 * std::cos(1e-4);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_LE(planner.getAccelerationBase().norm(), 3 + 1e-7);
|
||||
EXPECT_LE(planner.getJerkBase().norm(), .01 + 1e-7);
|
||||
}
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-10);
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) {
|
||||
LgvSCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const double period = i % 2 ? .0005 : .001;
|
||||
planner.plan(y(.08), LgvCartesianFrame::Base, period, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) {
|
||||
LgvSCurvePlanner actual;
|
||||
actual.setLinearConstraints(.05, 1e-6, .001);
|
||||
actual.initialize(y(.0499995));
|
||||
actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
auto reference = actual;
|
||||
// Removing the small acceleration with this jerk would exceed vmax.
|
||||
// A numerical "near zero" test must not accept and freeze this state.
|
||||
EXPECT_THROW(actual.setLinearConstraints(.05, 1e-6, 1e-8), std::runtime_error);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const Twist a = actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const Twist b = reference.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_DOUBLE_EQ((a - b).norm(), 0);
|
||||
EXPECT_LE(actual.getJerkBase().norm(), .001 + 1e-7);
|
||||
}
|
||||
EXPECT_NEAR(actual.getTwistBase().y(), .05, 1e-12);
|
||||
}
|
||||
|
||||
TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) {
|
||||
LgvSCurvePlanner seed;
|
||||
seed.setLinearConstraints(1, 3, 10);
|
||||
seed.setAngularConstraints(1, 3, 10);
|
||||
Twist target = y(.08);
|
||||
target[5] = .12;
|
||||
for (int i = 0; i < 80; ++i)
|
||||
seed.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
|
||||
const auto expect_unchanged = [&](auto operation) {
|
||||
auto expected = seed;
|
||||
auto actual = seed;
|
||||
EXPECT_THROW(operation(actual), std::invalid_argument);
|
||||
const auto compare_state = [&] {
|
||||
EXPECT_DOUBLE_EQ((actual.getTwistBase() - expected.getTwistBase()).norm(), 0);
|
||||
EXPECT_DOUBLE_EQ((actual.getAccelerationBase() - expected.getAccelerationBase()).norm(), 0);
|
||||
EXPECT_DOUBLE_EQ((actual.getJerkBase() - expected.getJerkBase()).norm(), 0);
|
||||
EXPECT_EQ(actual.isMoving(), expected.isMoving());
|
||||
EXPECT_EQ(actual.continuousLinearReversalEnabled(), expected.continuousLinearReversalEnabled());
|
||||
};
|
||||
compare_state();
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
const auto expected_twist = expected.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const auto actual_twist = actual.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_DOUBLE_EQ((actual_twist - expected_twist).norm(), 0);
|
||||
compare_state();
|
||||
}
|
||||
};
|
||||
const double nan = std::numeric_limits<double>::quiet_NaN();
|
||||
const double inf = std::numeric_limits<double>::infinity();
|
||||
for (double invalid : {-1., 0., nan, inf}) {
|
||||
SCOPED_TRACE(::testing::Message() << "invalid=" << invalid);
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
SCOPED_TRACE(index);
|
||||
double limits[] = {1, 3, 10};
|
||||
limits[index] = invalid;
|
||||
expect_unchanged([&](auto& p) { p.setLinearConstraints(limits[0], limits[1], limits[2]); });
|
||||
expect_unchanged([&](auto& p) { p.setAngularConstraints(limits[0], limits[1], limits[2]); });
|
||||
}
|
||||
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); });
|
||||
if (invalid != 0) {
|
||||
expect_unchanged([&](auto& p) { p.setLinearTargetReplanThreshold(invalid); });
|
||||
expect_unchanged([&](auto& p) { p.setAngularTargetReplanThreshold(invalid); });
|
||||
}
|
||||
}
|
||||
for (double invalid : {nan, inf}) {
|
||||
for (int index : {0, 5}) {
|
||||
Twist invalid_twist = target;
|
||||
invalid_twist[index] = invalid;
|
||||
expect_unchanged([&](auto& p) { p.initialize(invalid_twist); });
|
||||
expect_unchanged([&](auto& p) { p.plan(invalid_twist, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); });
|
||||
}
|
||||
Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity();
|
||||
invalid_rotation(1, 2) = invalid;
|
||||
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Tool, dt, invalid_rotation); });
|
||||
}
|
||||
// Over-limit initialization must not clamp only the internal scalar or
|
||||
// reset linear motion before discovering an invalid angular component.
|
||||
for (int index : {0, 5}) {
|
||||
Twist initial = y(.2);
|
||||
initial[index] = 2;
|
||||
expect_unchanged([&](auto& p) { p.initialize(initial); });
|
||||
}
|
||||
expect_unchanged([&](auto& p) { p.setLinearConstraints(.001, 3, 10); });
|
||||
expect_unchanged([&](auto& p) { p.setLinearConstraints(1, .01, 10); });
|
||||
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); });
|
||||
expect_unchanged([&](auto& p) { p.plan(target, static_cast<LgvCartesianFrame>(9), dt, Eigen::Matrix3d::Identity()); });
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
62
cmvr-es/algorithms/planner/joint/joint_path_planner.h
Normal file
62
cmvr-es/algorithms/planner/joint/joint_path_planner.h
Normal file
@ -0,0 +1,62 @@
|
||||
#ifndef CMVR_ES_JOINT_PATH_PLANNER_H
|
||||
#define CMVR_ES_JOINT_PATH_PLANNER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
using JointPath = std::vector<std::vector<double>>;
|
||||
|
||||
struct JointPathRequest {
|
||||
// All vectors use the same joint order and radians. Bounded revolute joints
|
||||
// only; continuous joints require a different state space.
|
||||
std::vector<double> start;
|
||||
std::vector<double> goal;
|
||||
std::vector<double> lower_bounds;
|
||||
std::vector<double> 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<bool(const std::vector<double>&)> is_state_valid;
|
||||
std::function<bool()> 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
|
||||
@ -0,0 +1,48 @@
|
||||
#ifndef CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H
|
||||
#define CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H
|
||||
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
|
||||
#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<JointPathPlanner> 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<RrtConnect>(options);
|
||||
}
|
||||
case config::JOINT_PATH_ALGORITHM_UNKNOWN:
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
#endif // CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H
|
||||
28
cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h
Normal file
28
cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h
Normal file
@ -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
|
||||
262
cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp
Normal file
262
cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp
Normal file
@ -0,0 +1,262 @@
|
||||
#include "algorithms/planner/joint/ompl/include/rrt_connect.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
|
||||
#include <ompl/base/MotionValidator.h>
|
||||
#include <ompl/base/ScopedState.h>
|
||||
#include <ompl/base/spaces/RealVectorStateSpace.h>
|
||||
#include <ompl/geometric/SimpleSetup.h>
|
||||
#include <ompl/geometric/planners/rrt/RRTConnect.h>
|
||||
|
||||
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<ob::State*, double> last_valid{nullptr, 0.0};
|
||||
return checkMotion(from, to, last_valid);
|
||||
}
|
||||
|
||||
bool checkMotion(const ob::State* from, const ob::State* to,
|
||||
std::pair<ob::State*, double>& last_valid) const override
|
||||
{
|
||||
const auto* a = from->as<ob::RealVectorStateSpace::StateType>();
|
||||
const auto* b = to->as<ob::RealVectorStateSpace::StateType>();
|
||||
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::size_t>(
|
||||
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<double>(i) / segments;
|
||||
si_->getStateSpace()->interpolate(from, to, fraction, sample.get());
|
||||
if (!si_->isValid(sample.get())) {
|
||||
last_valid.second = static_cast<double>(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<double>(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<unsigned int>::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<double>::max())) {
|
||||
return finish(JointPathStatus::InvalidRequest, "Joint-space extent is too large");
|
||||
}
|
||||
const auto in_bounds = [&](const std::vector<double>& 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<double>(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<double>& 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<ob::RealVectorStateSpace>(static_cast<unsigned int>(dof));
|
||||
ob::RealVectorBounds bounds(static_cast<unsigned int>(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<ob::RealVectorStateSpace::StateType>()->values;
|
||||
return valid(std::vector<double>(values, values + dof));
|
||||
});
|
||||
setup.getSpaceInformation()->setMotionValidator(
|
||||
std::make_shared<JointMotionValidator>(
|
||||
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<og::RRTConnect>(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<ob::RealVectorStateSpace::StateType>()->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
|
||||
@ -0,0 +1,222 @@
|
||||
#include "algorithms/planner/joint/joint_path_planner_factory.h"
|
||||
#include "algorithms/collision_detection/include/collision_checker.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <ompl/util/RandomNumbers.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
class RrtConnectSelfCollisionTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override
|
||||
{
|
||||
const std::vector<std::string> 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<double> 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"(<robot name="planar_obstacle_test">
|
||||
<link name="base"/>
|
||||
<link name="x_carriage"/>
|
||||
<link name="tool">
|
||||
<collision><geometry><box size="0.1 0.1 0.1"/></geometry></collision>
|
||||
</link>
|
||||
<joint name="x" type="prismatic">
|
||||
<parent link="base"/><child link="x_carriage"/><axis xyz="1 0 0"/>
|
||||
<limit lower="-1" upper="1" effort="1" velocity="1"/>
|
||||
</joint>
|
||||
<joint name="y" type="prismatic">
|
||||
<parent link="x_carriage"/><child link="tool"/><axis xyz="0 1 0"/>
|
||||
<limit lower="-1" upper="1" effort="1" velocity="1"/>
|
||||
</joint>
|
||||
</robot>)";
|
||||
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<double>{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<int>(std::ceil(extent / 0.0005)));
|
||||
for (int sample = 0; sample <= samples; ++sample) {
|
||||
const double ratio = static_cast<double>(sample) / samples;
|
||||
const std::vector<double> 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();
|
||||
}
|
||||
304
cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp
Normal file
304
cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp
Normal file
@ -0,0 +1,304 @@
|
||||
#include "algorithms/planner/joint/joint_path_planner_factory.h"
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <google/protobuf/text_format.h>
|
||||
#include <ompl/util/RandomNumbers.h>
|
||||
|
||||
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::size_t>(std::ceil(distance / 0.002)) + 1;
|
||||
for (std::size_t sample = 0; sample <= count; ++sample) {
|
||||
std::vector<double> 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<JointPathPlanner> 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<double>::quiet_NaN();
|
||||
EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest);
|
||||
request = freeSpaceRequest();
|
||||
request.upper_bounds[0] = std::numeric_limits<double>::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<double>::infinity(),
|
||||
std::numeric_limits<double>::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<config::JointPathAlgorithm>(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();
|
||||
}
|
||||
11
cmvr-es/algorithms/smoother/CMakeLists.txt
Normal file
11
cmvr-es/algorithms/smoother/CMakeLists.txt
Normal file
@ -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)
|
||||
@ -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<std::vector<double>>& waypoints,
|
||||
const MotionOptions& limits,
|
||||
double sample_period_s,
|
||||
JointTrajectory& output) const override;
|
||||
|
||||
private:
|
||||
double control_point_spacing_rad_;
|
||||
bool initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
128
cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp
Normal file
128
cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp
Normal file
@ -0,0 +1,128 @@
|
||||
#include "algorithms/smoother/bspline/include/bspline_smoother.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
|
||||
#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<std::vector<double>>& 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<double> 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<double>(dof, limits.acceleration),
|
||||
std::vector<double>(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<std::size_t>(count) + 1);
|
||||
const auto as_vector = [](const Eigen::VectorXd& value) {
|
||||
return std::vector<double>(value.data(), value.data() + value.size());
|
||||
};
|
||||
for (std::size_t i = 0; i <= static_cast<std::size_t>(count); ++i) {
|
||||
if (limits.cancellation_requested && limits.cancellation_requested()) return false;
|
||||
JointTrajectoryPoint point;
|
||||
point.time_s = i == static_cast<std::size_t>(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<double, std::milli>(
|
||||
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
|
||||
@ -0,0 +1,519 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#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<double>(i) /
|
||||
static_cast<double>(point_count - 1);
|
||||
JointTrajectoryPoint point;
|
||||
point.time_s = static_cast<double>(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<double>& lhs,
|
||||
const std::vector<double>& rhs)
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return std::numeric_limits<double>::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<double> start{0.12, -0.2, 0.4, 0.15};
|
||||
const std::vector<double> 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<std::vector<double>> 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<double>::quiet_NaN();
|
||||
const double inf = std::numeric_limits<double>::infinity();
|
||||
JointTrajectory trajectory;
|
||||
const auto reject = [&](const std::vector<std::vector<double>>& 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<std::vector<double>>{
|
||||
{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::size_t>(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<double>(i) / static_cast<double>(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<std::vector<std::vector<double>>> 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<double> velocity{0.3, 0.15, 0.08};
|
||||
const std::vector<double> acceleration{0.8, 0.5, 0.3};
|
||||
const std::vector<double> 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<double> start{0.12, -0.2, 0.4}, delta{0.8, -0.4, 0.2};
|
||||
std::vector<std::vector<double>> waypoints;
|
||||
for (const double progress : {0.0, 0.002, 0.03, 0.4, 0.83, 1.0}) {
|
||||
std::vector<double> 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<std::vector<double>> 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<std::vector<double>> 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<std::vector<std::vector<double>>> 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<double> 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<double>(3, 100.0), 0.01);
|
||||
const double reference_duration = reference->timeInterval()[1];
|
||||
double previous_duration = std::numeric_limits<double>::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<double>(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<std::vector<double>> 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<std::vector<double>> path{{0.0, 0.0}, {0.2, -0.1}};
|
||||
const std::vector<double> limits{1.0, 1.0};
|
||||
const double nan = std::numeric_limits<double>::quiet_NaN();
|
||||
const double inf = std::numeric_limits<double>::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<std::vector<double>>{{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
|
||||
24
cmvr-es/algorithms/smoother/joint_trajectory_smoother.h
Normal file
24
cmvr-es/algorithms/smoother/joint_trajectory_smoother.h
Normal file
@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#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<std::vector<double>>& waypoints,
|
||||
const MotionOptions& limits,
|
||||
double sample_period_s,
|
||||
JointTrajectory& output) const = 0;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#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<JointTrajectorySmoother> create(
|
||||
const config::JointTrajectorySmootherConfig& cfg)
|
||||
{
|
||||
if (!cfg.has_quintic_bspline()) {
|
||||
return nullptr;
|
||||
}
|
||||
const auto& spline = cfg.quintic_bspline();
|
||||
auto smoother = std::make_shared<BSplineSmoother>(
|
||||
spline.has_control_point_spacing_rad() ? spline.control_point_spacing_rad() : 0.05);
|
||||
if (!smoother->init()) {
|
||||
return nullptr;
|
||||
}
|
||||
return smoother;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
134
cmvr-es/algorithms/smoother/joint_trajectory_validation.h
Normal file
134
cmvr-es/algorithms/smoother/joint_trajectory_validation.h
Normal file
@ -0,0 +1,134 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
inline bool validateJointTrajectory(
|
||||
const JointTrajectory& trajectory,
|
||||
const std::size_t expected_dof,
|
||||
const MotionOptions& limits)
|
||||
{
|
||||
if (trajectory.size() < 2 || expected_dof == 0) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory must contain at least "
|
||||
"two points and have a non-zero DOF";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(limits.velocity) || limits.velocity <= 0.0 ||
|
||||
!std::isfinite(limits.acceleration) || limits.acceleration <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity or acceleration limit is invalid";
|
||||
return false;
|
||||
}
|
||||
if (!limits.joint_velocity_limits.empty() &&
|
||||
limits.joint_velocity_limits.size() != expected_dof) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] joint velocity limit count does not match DOF";
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr double kVelocityTolerance = 1e-6;
|
||||
constexpr double kAccelerationTolerance = 1e-3;
|
||||
double maximum_velocity = 0.0;
|
||||
double maximum_acceleration = 0.0;
|
||||
double maximum_position_velocity = 0.0;
|
||||
double maximum_position_acceleration = 0.0;
|
||||
double maximum_jerk = 0.0;
|
||||
std::vector<double> previous_position_velocity(expected_dof, 0.0);
|
||||
std::vector<double> previous_acceleration(expected_dof, 0.0);
|
||||
|
||||
for (std::size_t i = 0; i < trajectory.size(); ++i) {
|
||||
const auto& point = trajectory[i];
|
||||
if (!std::isfinite(point.time_s) ||
|
||||
point.position.size() != expected_dof ||
|
||||
point.velocity.size() != expected_dof) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid trajectory point at index=" << i;
|
||||
return false;
|
||||
}
|
||||
|
||||
double dt = 0.0;
|
||||
if (i > 0) {
|
||||
dt = point.time_s - trajectory[i - 1].time_s;
|
||||
if (!std::isfinite(dt) || dt <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory time is not increasing at index="
|
||||
<< i;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (std::size_t joint = 0; joint < expected_dof; ++joint) {
|
||||
if (!std::isfinite(point.position[joint]) ||
|
||||
!std::isfinite(point.velocity[joint])) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] non-finite trajectory value at point="
|
||||
<< i << ", joint=" << joint;
|
||||
return false;
|
||||
}
|
||||
|
||||
const double velocity = std::abs(point.velocity[joint]);
|
||||
const double velocity_limit = limits.joint_velocity_limits.empty()
|
||||
? limits.velocity
|
||||
: limits.joint_velocity_limits[joint];
|
||||
if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid velocity limit for joint="
|
||||
<< joint;
|
||||
return false;
|
||||
}
|
||||
maximum_velocity = std::max(maximum_velocity, velocity);
|
||||
if (velocity > velocity_limit + kVelocityTolerance) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity limit exceeded at point="
|
||||
<< i << ", joint=" << joint
|
||||
<< ", actual=" << velocity
|
||||
<< ", limit=" << velocity_limit;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
const double position_velocity =
|
||||
(point.position[joint] - trajectory[i - 1].position[joint]) / dt;
|
||||
const double acceleration =
|
||||
(point.velocity[joint] - trajectory[i - 1].velocity[joint]) / dt;
|
||||
maximum_position_velocity = std::max(
|
||||
maximum_position_velocity, std::abs(position_velocity));
|
||||
maximum_acceleration = std::max(
|
||||
maximum_acceleration, std::abs(acceleration));
|
||||
if (std::abs(acceleration) >
|
||||
limits.acceleration + kAccelerationTolerance) {
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] acceleration limit exceeded at point="
|
||||
<< i << ", joint=" << joint
|
||||
<< ", actual=" << std::abs(acceleration)
|
||||
<< ", limit=" << limits.acceleration;
|
||||
return false;
|
||||
}
|
||||
if (i > 1) {
|
||||
// Interval-average derivatives are located at interval midpoints.
|
||||
const double midpoint_dt = 0.5 * (point.time_s - trajectory[i - 2].time_s);
|
||||
maximum_position_acceleration = std::max(
|
||||
maximum_position_acceleration,
|
||||
std::abs(position_velocity -
|
||||
previous_position_velocity[joint]) / midpoint_dt);
|
||||
maximum_jerk = std::max(
|
||||
maximum_jerk,
|
||||
std::abs(acceleration - previous_acceleration[joint]) / midpoint_dt);
|
||||
}
|
||||
previous_position_velocity[joint] = position_velocity;
|
||||
previous_acceleration[joint] = acceleration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CMVR_LOG(INFO) << "[JointTrajectoryValidation] trajectory validated"
|
||||
<< ", points=" << trajectory.size()
|
||||
<< ", max_velocity_rad_s=" << maximum_velocity
|
||||
<< ", max_discrete_acceleration_rad_s2=" << maximum_acceleration
|
||||
<< ", max_position_velocity_rad_s=" << maximum_position_velocity
|
||||
<< ", max_position_acceleration_rad_s2="
|
||||
<< maximum_position_acceleration
|
||||
<< ", max_discrete_jerk_rad_s3=" << maximum_jerk;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -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<double, Eigen::Dynamic, 1> 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() {
|
||||
|
||||
@ -7,7 +7,11 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
using ::cmvr::JointLimit;
|
||||
using ::cmvr::RobotModel;
|
||||
|
||||
enum class ArmErrorCode {
|
||||
OK = 0,
|
||||
@ -72,8 +76,8 @@ struct SpeedLOptions {
|
||||
// Requested linear jerk (m/s^3), capped by the arm's configured maximum.
|
||||
// Unset uses that maximum.
|
||||
std::optional<double> 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<bool> continuous_linear_reversal;
|
||||
// Capture the first applied command's measured TCP position and target
|
||||
// direction in Base. Useful for distance-based motion without caller FK.
|
||||
@ -96,37 +100,6 @@ struct CartesianWrench {
|
||||
double tz{0.0};
|
||||
};
|
||||
|
||||
struct JointLimit {
|
||||
double lower{0.0};
|
||||
double upper{0.0};
|
||||
double max_velocity{0.0};
|
||||
double max_acceleration{0.0};
|
||||
double max_torque{0.0};
|
||||
};
|
||||
|
||||
struct RobotModel {
|
||||
std::string name;
|
||||
std::string subtype;
|
||||
std::string manufacturer;
|
||||
std::string serial_number;
|
||||
std::string description_id;
|
||||
std::string default_base_frame;
|
||||
std::string default_tcp_frame;
|
||||
bool detected_from_sdk{false};
|
||||
std::size_t dof{0};
|
||||
std::vector<std::string> joint_names;
|
||||
std::vector<JointLimit> 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<double> position;
|
||||
std::vector<double> velocity;
|
||||
@ -146,6 +119,9 @@ struct JointTrajectoryPoint {
|
||||
double time_s{0.0};
|
||||
std::vector<double> position;
|
||||
std::vector<double> velocity;
|
||||
// Analytic derivatives; empty for trajectories without these derivatives.
|
||||
std::vector<double> acceleration;
|
||||
std::vector<double> jerk;
|
||||
};
|
||||
|
||||
using JointTrajectory = std::vector<JointTrajectoryPoint>;
|
||||
@ -192,12 +168,21 @@ struct MotionOptions {
|
||||
double velocity{0.0};
|
||||
double acceleration{0.0};
|
||||
double blend_radius{0.0};
|
||||
double jerk{5.0};
|
||||
double jerk{300.0};
|
||||
std::vector<double> 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<bool()> 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<void(const JointTrajectory&)> 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<bool(const CartesianPose&)> is_tcp_pose_valid;
|
||||
};
|
||||
|
||||
struct ServoOptions {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# 六轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。
|
||||
# 七轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "tchl_arm"
|
||||
@ -6,29 +6,24 @@ arm {
|
||||
motor {
|
||||
motor_system_id: "tchl_joint_motors"
|
||||
motor_group_ids: "tchl_joint_motors"
|
||||
dof: 6
|
||||
dof: 7
|
||||
joint_names: "TCHL_AXIS_1"
|
||||
joint_names: "TCHL_AXIS_2"
|
||||
joint_names: "TCHL_AXIS_3"
|
||||
joint_names: "TCHL_AXIS_4"
|
||||
joint_names: "TCHL_AXIS_5"
|
||||
joint_names: "TCHL_AXIS_6"
|
||||
joint_names: "TCHL_AXIS_7"
|
||||
upd_freq: 1000
|
||||
}
|
||||
|
||||
motion {
|
||||
# 保持 linbo_dev 的 TOPPRA 规划器,不引入另一分支的规划接口。
|
||||
# 与 lgv_dev_tc_motor 一致:默认五次 B 样条平滑,采样周期 1 ms。
|
||||
move_j {
|
||||
settle_timeout_s: 2.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,6 +31,7 @@ motor {
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
slaves { motor_id: 5 alias: 0 position: 4 }
|
||||
slaves { motor_id: 6 alias: 0 position: 5 }
|
||||
slaves { motor_id: 7 alias: 0 position: 6 }
|
||||
|
||||
}
|
||||
|
||||
@ -44,7 +45,8 @@ motor {
|
||||
joints { joint_name: "TCHL_AXIS_3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_4" q_lb: -2.04 q_ub: 1.10 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 0.21 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_7" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
|
||||
}
|
||||
|
||||
@ -55,6 +57,7 @@ motor {
|
||||
motors { id: 4 joint_name: "TCHL_AXIS_4" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 5 joint_name: "TCHL_AXIS_5" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 6 joint_name: "TCHL_AXIS_6" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 7 joint_name: "TCHL_AXIS_7" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
10
cmvr-es/curves/CMakeLists.txt
Normal file
10
cmvr-es/curves/CMakeLists.txt
Normal file
@ -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)
|
||||
56
cmvr-es/curves/bspline/include/quintic_bspline.h
Normal file
56
cmvr-es/curves/bspline/include/quintic_bspline.h
Normal file
@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Dense>
|
||||
|
||||
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<QuinticBSpline> create(
|
||||
const std::vector<std::vector<double>>& waypoints,
|
||||
const std::vector<double>& velocity_limits,
|
||||
const std::vector<double>& acceleration_limits,
|
||||
const std::vector<double>& jerk_limits,
|
||||
double minimum_duration_s,
|
||||
const std::function<bool()>& 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<double> 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<double>& knots() const { return knots_[0]; }
|
||||
|
||||
private:
|
||||
QuinticBSpline() = default;
|
||||
Eigen::VectorXd evaluate(double t, int order) const;
|
||||
|
||||
std::array<Eigen::MatrixXd, 4> controls_;
|
||||
std::array<std::vector<double>, 4> knots_;
|
||||
double duration_s_{0.0};
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
264
cmvr-es/curves/bspline/src/quintic_bspline.cpp
Normal file
264
cmvr-es/curves/bspline/src/quintic_bspline.cpp
Normal file
@ -0,0 +1,264 @@
|
||||
#include "curves/bspline/include/quintic_bspline.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
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<bool()>& cancelled)
|
||||
{
|
||||
if (cancelled && cancelled()) {
|
||||
throw std::runtime_error("B-spline planning cancelled");
|
||||
}
|
||||
}
|
||||
|
||||
void validateLimits(const std::vector<double>& 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<double>& knots, std::size_t index)
|
||||
{
|
||||
const bool mirror = knots[index + 3] > 0.5;
|
||||
std::array<double, 6> 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> QuinticBSpline::create(
|
||||
const std::vector<std::vector<double>>& waypoints,
|
||||
const std::vector<double>& velocity_limits,
|
||||
const std::vector<double>& acceleration_limits,
|
||||
const std::vector<double>& jerk_limits,
|
||||
double minimum_duration_s,
|
||||
const std::function<bool()>& 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::size_t>(std::numeric_limits<Eigen::Index>::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<Eigen::VectorXd> vertices;
|
||||
std::vector<double> 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<const Eigen::VectorXd>(
|
||||
waypoint.data(), static_cast<Eigen::Index>(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<long double>(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<std::size_t>(1, static_cast<std::size_t>(interval_count));
|
||||
const auto control_count = intervals + kDegree;
|
||||
auto trajectory = std::shared_ptr<QuinticBSpline>(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<double>(i - kDegree) / intervals;
|
||||
}
|
||||
std::fill(knots.begin() + static_cast<std::ptrdiff_t>(control_count), knots.end(), 1.0);
|
||||
|
||||
auto& controls = trajectory->controls_[0];
|
||||
controls.resize(static_cast<Eigen::Index>(dof), static_cast<Eigen::Index>(control_count));
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
controls.col(i) = vertices.front();
|
||||
controls.col(static_cast<Eigen::Index>(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<Eigen::Index>(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<long double>(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<long double>(minimum_duration_s), required_duration * kDurationMargin);
|
||||
if (!std::isfinite(duration) || duration > std::numeric_limits<double>::max()) {
|
||||
throw std::runtime_error("B-spline duration is not representable");
|
||||
}
|
||||
trajectory->duration_s_ = static_cast<double>(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<Eigen::Index>(
|
||||
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<double> QuinticBSpline::knotTimes() const
|
||||
{
|
||||
std::vector<double> 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
|
||||
262
cmvr-es/curves/s_curve/include/s_curve.h
Normal file
262
cmvr-es/curves/s_curve/include/s_curve.h
Normal file
@ -0,0 +1,262 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/2.
|
||||
//
|
||||
/**
|
||||
* @file s_curve.h
|
||||
* @brief 位置与速度 S 曲线的数学计算
|
||||
*
|
||||
* 实现标准 7 段式位置 S 曲线速度剖面:
|
||||
* 1. 加加速度上升段(加速度逐渐增大)
|
||||
* 2. 匀加速段
|
||||
* 3. 加加速度下降段(加速度逐渐降到 0)
|
||||
* 4. 匀速巡航段
|
||||
* 5. 加加速度下降段(减速度逐渐增大)
|
||||
* 6. 匀减速段
|
||||
* 7. 加加速度上升段(减速度逐渐降到 0)
|
||||
*
|
||||
* 同时支持三段式速度切换剖面。只负责剖面计算与按时间采样,
|
||||
* 不保存运行状态,不负责实时目标更新、周期推进或反馈同步。
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief 单次点到点运动的 S 曲线剖面参数
|
||||
*/
|
||||
struct LgvSCurveProfile
|
||||
{
|
||||
// 7 个阶段的持续时间
|
||||
double t1; // 加加速度上升时间(加速阶段)
|
||||
double t2; // 匀加速时间
|
||||
double t3; // 加加速度下降时间(加速阶段结束)
|
||||
double t4; // 匀速时间(巡航)
|
||||
double t5; // 加加速度下降时间(减速阶段)
|
||||
double t6; // 匀减速时间
|
||||
double t7; // 加加速度上升时间(减速阶段结束)
|
||||
|
||||
double total_time;
|
||||
|
||||
// 运动约束
|
||||
double j_max; // 最大加加速度 (rad/s³)
|
||||
double a_max; // 最大加速度 (rad/s²)
|
||||
double v_max; // 最大速度 (rad/s)
|
||||
|
||||
// 运动参数
|
||||
double distance; // 运动总距离
|
||||
double direction; // +1 或 -1
|
||||
double v_cruise; // 实际达到的巡航速度
|
||||
double a_limit; // 实际达到的加速度上限
|
||||
|
||||
// 初始条件
|
||||
double p0; // 初始位置
|
||||
double v0; // 初始速度
|
||||
double a0; // 初始加速度
|
||||
double vf; // 终止速度
|
||||
|
||||
LgvSCurveProfile()
|
||||
: t1(0), t2(0), t3(0), t4(0), t5(0), t6(0), t7(0)
|
||||
, total_time(0)
|
||||
, j_max(50.0), a_max(10.0), v_max(3.0)
|
||||
, distance(0), direction(1.0), v_cruise(0), a_limit(0)
|
||||
, p0(0), v0(0), a0(0), vf(0)
|
||||
{}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 单次速度切换的 S 曲线剖面参数
|
||||
*
|
||||
* 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile:
|
||||
*
|
||||
* seg1: jerk = j1, duration = t1
|
||||
* seg2: jerk = j2, duration = t2 (当前实现 j2 = 0)
|
||||
* seg3: jerk = j3, duration = t3
|
||||
*
|
||||
* 其中 j1/j3 为 ±j_max,j2 为 0。
|
||||
*/
|
||||
struct LgvSCurveVelocityProfile
|
||||
{
|
||||
double t1;
|
||||
double t2;
|
||||
double t3;
|
||||
|
||||
double total_time;
|
||||
|
||||
double j1;
|
||||
double j2;
|
||||
double j3;
|
||||
|
||||
double v0;
|
||||
double a0;
|
||||
double vf;
|
||||
|
||||
bool valid;
|
||||
|
||||
LgvSCurveVelocityProfile()
|
||||
: t1(0.0), t2(0.0), t3(0.0)
|
||||
, total_time(0.0)
|
||||
, j1(0.0), j2(0.0), j3(0.0)
|
||||
, v0(0.0), a0(0.0), vf(0.0)
|
||||
, valid(false)
|
||||
{}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 位置与速度 S 曲线的数学计算和采样,不保存运行状态
|
||||
*/
|
||||
class LgvSCurve
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief 构造函数(带运动约束)
|
||||
* @param max_velocity 最大速度 (rad/s)
|
||||
* @param max_acceleration 最大加速度 (rad/s²)
|
||||
* @param max_jerk 最大加加速度 (rad/s³)
|
||||
*/
|
||||
LgvSCurve(double max_velocity = 3.0,
|
||||
double max_acceleration = 10.0,
|
||||
double max_jerk = 50.0);
|
||||
|
||||
/**
|
||||
* @brief 设置运动约束
|
||||
*/
|
||||
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
|
||||
|
||||
/**
|
||||
* @brief 获取当前运动约束
|
||||
*/
|
||||
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
|
||||
|
||||
/**
|
||||
* @brief 计算点到点运动的完整 S 曲线剖面
|
||||
* @param start_position 起始位置
|
||||
* @param end_position 终止位置
|
||||
* @param start_velocity 起始速度(默认 0)
|
||||
* @param end_velocity 终止速度(默认 0)
|
||||
* @return 计算得到的剖面参数
|
||||
*/
|
||||
LgvSCurveProfile calculatePositionProfile(double start_position, double end_position,
|
||||
double start_velocity = 0.0,
|
||||
double end_velocity = 0.0) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的位置
|
||||
* @param profile S 曲线剖面
|
||||
* @param t 从起点开始的时间
|
||||
* @return 时刻 t 的位置
|
||||
*/
|
||||
double getPositionAtTime(const LgvSCurveProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的速度
|
||||
* @param profile S 曲线剖面
|
||||
* @param t 从起点开始的时间
|
||||
* @return 时刻 t 的速度
|
||||
*/
|
||||
double getVelocityAtTime(const LgvSCurveProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的加速度
|
||||
* @param profile S 曲线剖面
|
||||
* @param t 从起点开始的时间
|
||||
* @return 时刻 t 的加速度
|
||||
*/
|
||||
double getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的加加速度
|
||||
* @param profile S 曲线剖面
|
||||
* @param t 从起点开始的时间
|
||||
* @return 时刻 t 的加加速度
|
||||
*/
|
||||
double getJerkAtTime(const LgvSCurveProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 按固定时间间隔生成轨迹点
|
||||
* @param profile S 曲线剖面
|
||||
* @param dt 轨迹点时间间隔
|
||||
* @param positions 输出:每个时间点的位置
|
||||
* @param velocities 输出:每个时间点的速度
|
||||
* @param accelerations 输出:每个时间点的加速度
|
||||
*/
|
||||
void generateTrajectory(const LgvSCurveProfile& profile, double dt,
|
||||
std::vector<double>& positions,
|
||||
std::vector<double>& velocities,
|
||||
std::vector<double>& accelerations) const;
|
||||
|
||||
/**
|
||||
* @brief 计算单次速度切换剖面
|
||||
*/
|
||||
LgvSCurveVelocityProfile calculateVelocityProfile(double start_velocity,
|
||||
double end_velocity,
|
||||
double start_acceleration = 0.0) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的速度
|
||||
*/
|
||||
double getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的加速度
|
||||
*/
|
||||
double getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的 jerk
|
||||
*/
|
||||
double getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 按固定时间间隔生成轨迹点
|
||||
*/
|
||||
void generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt,
|
||||
std::vector<double>& velocities,
|
||||
std::vector<double>& accelerations,
|
||||
std::vector<double>& jerks) const;
|
||||
|
||||
private:
|
||||
double max_velocity_;
|
||||
double max_acceleration_;
|
||||
double max_jerk_;
|
||||
|
||||
static constexpr double EPSILON = 1e-9;
|
||||
static constexpr double VELOCITY_THRESHOLD = 1e-6;
|
||||
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
|
||||
|
||||
double computeSegmentJerk(const LgvSCurveProfile& profile, double t) const;
|
||||
void calculateShortProfile(LgvSCurveProfile& profile) const;
|
||||
void calculateLongProfile(LgvSCurveProfile& profile) const;
|
||||
|
||||
/**
|
||||
* @brief 判断 profile 是否满足速度上限
|
||||
*/
|
||||
bool isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const;
|
||||
|
||||
/**
|
||||
* @brief 计算完整剖面终点状态
|
||||
*/
|
||||
void integrateWholeProfile(const LgvSCurveVelocityProfile& profile,
|
||||
double& v_end,
|
||||
double& a_end) const;
|
||||
|
||||
static double clamp(double value, double min_val, double max_val)
|
||||
{
|
||||
return std::max(min_val, std::min(max_val, value));
|
||||
}
|
||||
|
||||
static double sign(double value)
|
||||
{
|
||||
if (value > EPSILON) return 1.0;
|
||||
if (value < -EPSILON) return -1.0;
|
||||
return 0.0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
874
cmvr-es/curves/s_curve/src/s_curve.cpp
Normal file
874
cmvr-es/curves/s_curve/src/s_curve.cpp
Normal file
@ -0,0 +1,874 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/2.
|
||||
//
|
||||
|
||||
|
||||
/**
|
||||
* @file s_curve.cpp
|
||||
* @brief 位置与速度 S 曲线数学实现
|
||||
*/
|
||||
|
||||
#include "curves/s_curve/include/s_curve.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
LgvSCurve::LgvSCurve(double max_velocity, double max_acceleration, double max_jerk)
|
||||
: max_velocity_(std::abs(max_velocity))
|
||||
, max_acceleration_(std::abs(max_acceleration))
|
||||
, max_jerk_(std::abs(max_jerk))
|
||||
{}
|
||||
|
||||
void LgvSCurve::setConstraints(double max_velocity, double max_acceleration, double max_jerk)
|
||||
{
|
||||
max_velocity_ = std::abs(max_velocity);
|
||||
max_acceleration_ = std::abs(max_acceleration);
|
||||
max_jerk_ = std::abs(max_jerk);
|
||||
}
|
||||
|
||||
void LgvSCurve::getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const
|
||||
{
|
||||
max_velocity = max_velocity_;
|
||||
max_acceleration = max_acceleration_;
|
||||
max_jerk = max_jerk_;
|
||||
}
|
||||
|
||||
LgvSCurveProfile LgvSCurve::calculatePositionProfile(double start_position, double end_position,
|
||||
double start_velocity, double end_velocity) const
|
||||
{
|
||||
LgvSCurveProfile profile;
|
||||
profile.j_max = max_jerk_;
|
||||
profile.a_max = max_acceleration_;
|
||||
profile.v_max = max_velocity_;
|
||||
profile.p0 = start_position;
|
||||
profile.v0 = start_velocity;
|
||||
profile.a0 = 0.0; // Assume starting from zero acceleration
|
||||
profile.vf = end_velocity;
|
||||
|
||||
double displacement = end_position - start_position;
|
||||
profile.distance = std::abs(displacement);
|
||||
profile.direction = (displacement >= 0) ? 1.0 : -1.0;
|
||||
|
||||
if (profile.distance < EPSILON) {
|
||||
// 无需运动
|
||||
profile.total_time = 0.0;
|
||||
return profile;
|
||||
}
|
||||
|
||||
const double start_speed = profile.direction * start_velocity;
|
||||
const double end_speed = profile.direction * end_velocity;
|
||||
if (start_speed < -VELOCITY_THRESHOLD || end_speed < -VELOCITY_THRESHOLD) {
|
||||
profile.total_time = 0.0;
|
||||
return profile;
|
||||
}
|
||||
|
||||
if (std::abs(start_speed) > VELOCITY_THRESHOLD ||
|
||||
std::abs(end_speed) > VELOCITY_THRESHOLD) {
|
||||
auto calc_transition = [&](double v_from, double v_to,
|
||||
double& t_j, double& t_a,
|
||||
double& duration, double& distance) {
|
||||
t_j = 0.0;
|
||||
t_a = 0.0;
|
||||
duration = 0.0;
|
||||
distance = 0.0;
|
||||
|
||||
const double dv = std::abs(v_to - v_from);
|
||||
if (dv <= 1e-12 || profile.a_max <= 1e-12 || profile.j_max <= 1e-12) {
|
||||
return;
|
||||
}
|
||||
|
||||
const double dv_switch = profile.a_max * profile.a_max / profile.j_max;
|
||||
if (dv < dv_switch) {
|
||||
t_j = std::sqrt(dv / profile.j_max);
|
||||
t_a = 0.0;
|
||||
} else {
|
||||
t_j = profile.a_max / profile.j_max;
|
||||
t_a = dv / profile.a_max - t_j;
|
||||
}
|
||||
|
||||
duration = 2.0 * t_j + t_a;
|
||||
distance = 0.5 * (v_from + v_to) * duration;
|
||||
};
|
||||
|
||||
const double v_cap = std::max({profile.v_max, start_speed, end_speed});
|
||||
const double v_peak_min = std::max(start_speed, end_speed);
|
||||
|
||||
double acc_tj = 0.0, acc_ta = 0.0, acc_duration = 0.0, acc_distance = 0.0;
|
||||
double dec_tj = 0.0, dec_ta = 0.0, dec_duration = 0.0, dec_distance = 0.0;
|
||||
calc_transition(start_speed, v_peak_min,
|
||||
acc_tj, acc_ta, acc_duration, acc_distance);
|
||||
calc_transition(v_peak_min, end_speed,
|
||||
dec_tj, dec_ta, dec_duration, dec_distance);
|
||||
const double d_min = acc_distance + dec_distance;
|
||||
if (profile.distance + EPSILON < d_min) {
|
||||
profile.total_time = 0.0;
|
||||
return profile;
|
||||
}
|
||||
|
||||
calc_transition(start_speed, v_cap,
|
||||
acc_tj, acc_ta, acc_duration, acc_distance);
|
||||
calc_transition(v_cap, end_speed,
|
||||
dec_tj, dec_ta, dec_duration, dec_distance);
|
||||
const double d_cap = acc_distance + dec_distance;
|
||||
|
||||
double v_peak = v_cap;
|
||||
double t4 = 0.0;
|
||||
|
||||
if (profile.distance > d_cap + EPSILON) {
|
||||
t4 = (profile.distance - d_cap) / std::max(v_peak, EPSILON);
|
||||
} else {
|
||||
double lo = v_peak_min;
|
||||
double hi = v_cap;
|
||||
for (int iter = 0; iter < 80; ++iter) {
|
||||
const double mid = 0.5 * (lo + hi);
|
||||
double mid_acc_tj = 0.0, mid_acc_ta = 0.0, mid_acc_duration = 0.0, mid_acc_distance = 0.0;
|
||||
double mid_dec_tj = 0.0, mid_dec_ta = 0.0, mid_dec_duration = 0.0, mid_dec_distance = 0.0;
|
||||
calc_transition(start_speed, mid,
|
||||
mid_acc_tj, mid_acc_ta, mid_acc_duration, mid_acc_distance);
|
||||
calc_transition(mid, end_speed,
|
||||
mid_dec_tj, mid_dec_ta, mid_dec_duration, mid_dec_distance);
|
||||
const double d_mid = mid_acc_distance + mid_dec_distance;
|
||||
if (d_mid < profile.distance) {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
v_peak = hi;
|
||||
calc_transition(start_speed, v_peak,
|
||||
acc_tj, acc_ta, acc_duration, acc_distance);
|
||||
calc_transition(v_peak, end_speed,
|
||||
dec_tj, dec_ta, dec_duration, dec_distance);
|
||||
}
|
||||
|
||||
profile.t1 = acc_tj;
|
||||
profile.t2 = acc_ta;
|
||||
profile.t3 = acc_tj;
|
||||
profile.t4 = t4;
|
||||
profile.t5 = dec_tj;
|
||||
profile.t6 = dec_ta;
|
||||
profile.t7 = dec_tj;
|
||||
profile.v_cruise = v_peak;
|
||||
profile.a_limit = std::max(profile.j_max * profile.t1, profile.j_max * profile.t5);
|
||||
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
|
||||
profile.t5 + profile.t6 + profile.t7;
|
||||
return profile;
|
||||
}
|
||||
|
||||
const double j = profile.j_max;
|
||||
const double a = profile.a_max;
|
||||
const double v = profile.v_max;
|
||||
const double t_j_a = a / j;
|
||||
|
||||
if (v < a * t_j_a) {
|
||||
const double t_j_v = std::sqrt(v / j);
|
||||
const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v;
|
||||
if (profile.distance > s_min + EPSILON) {
|
||||
calculateLongProfile(profile);
|
||||
} else {
|
||||
calculateShortProfile(profile);
|
||||
}
|
||||
} else {
|
||||
const double t_a_v = v / a - t_j_a;
|
||||
const double s_half_v =
|
||||
a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a_v + 0.5 * t_a_v * t_a_v);
|
||||
const double s_min = 2.0 * s_half_v;
|
||||
if (profile.distance > s_min + EPSILON) {
|
||||
calculateLongProfile(profile);
|
||||
} else {
|
||||
calculateShortProfile(profile);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
}
|
||||
|
||||
void LgvSCurve::calculateShortProfile(LgvSCurveProfile& profile) const
|
||||
{
|
||||
// 短距离:无巡航段(t4 = 0)。
|
||||
const double j = profile.j_max;
|
||||
const double a = profile.a_max;
|
||||
const double v = profile.v_max;
|
||||
const double d = profile.distance;
|
||||
const double t_j_a = a / j;
|
||||
|
||||
if (v < a * t_j_a) {
|
||||
// 达不到 a_max:极短距离时只有 4 个 jerk 段。
|
||||
const double t1 = std::cbrt(d / (2.0 * j));
|
||||
profile.t1 = t1;
|
||||
profile.t2 = 0.0;
|
||||
profile.t3 = t1;
|
||||
profile.t4 = 0.0;
|
||||
profile.t5 = t1;
|
||||
profile.t6 = 0.0;
|
||||
profile.t7 = t1;
|
||||
profile.v_cruise = j * t1 * t1;
|
||||
profile.a_limit = j * t1;
|
||||
} else {
|
||||
// 能达到 a_max,但达不到 v_max:求无巡航的匀加速持续时间。
|
||||
const double D = t_j_a * t_j_a + 4.0 * (d / a);
|
||||
double t2 = (-3.0 * t_j_a + std::sqrt(std::max(0.0, D))) * 0.5;
|
||||
|
||||
if (t2 < 0.0) {
|
||||
const double t1 = std::cbrt(d / (2.0 * j));
|
||||
profile.t1 = t1;
|
||||
profile.t2 = 0.0;
|
||||
profile.t3 = t1;
|
||||
profile.t4 = 0.0;
|
||||
profile.t5 = t1;
|
||||
profile.t6 = 0.0;
|
||||
profile.t7 = t1;
|
||||
profile.v_cruise = j * t1 * t1;
|
||||
profile.a_limit = j * t1;
|
||||
} else {
|
||||
profile.t1 = t_j_a;
|
||||
profile.t2 = t2;
|
||||
profile.t3 = t_j_a;
|
||||
profile.t4 = 0.0;
|
||||
profile.t5 = t_j_a;
|
||||
profile.t6 = t2;
|
||||
profile.t7 = t_j_a;
|
||||
profile.v_cruise = a * (t2 + t_j_a);
|
||||
profile.a_limit = a;
|
||||
}
|
||||
}
|
||||
|
||||
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
|
||||
profile.t5 + profile.t6 + profile.t7;
|
||||
}
|
||||
|
||||
void LgvSCurve::calculateLongProfile(LgvSCurveProfile& profile) const
|
||||
{
|
||||
// 含巡航段的完整 7 段式 S 曲线;与 LgvSCurveProfile1D 的 full-profile 公式一致。
|
||||
const double j = profile.j_max;
|
||||
const double a = profile.a_max;
|
||||
const double v = profile.v_max;
|
||||
const double d = profile.distance;
|
||||
const double t_j_a = a / j;
|
||||
|
||||
if (v < a * t_j_a) {
|
||||
// 达不到 a_max,但可以达到 v_max 并进入巡航。
|
||||
const double t_j_v = std::sqrt(v / j);
|
||||
const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v;
|
||||
profile.t1 = t_j_v;
|
||||
profile.t2 = 0.0;
|
||||
profile.t3 = t_j_v;
|
||||
profile.t4 = std::max(0.0, (d - s_min) / v);
|
||||
profile.t5 = t_j_v;
|
||||
profile.t6 = 0.0;
|
||||
profile.t7 = t_j_v;
|
||||
profile.v_cruise = v;
|
||||
profile.a_limit = j * t_j_v;
|
||||
} else {
|
||||
// 能达到 a_max 和 v_max。
|
||||
const double t_a = v / a - t_j_a;
|
||||
const double s_half =
|
||||
a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a + 0.5 * t_a * t_a);
|
||||
const double s_min = 2.0 * s_half;
|
||||
|
||||
profile.t1 = t_j_a;
|
||||
profile.t2 = t_a;
|
||||
profile.t3 = t_j_a;
|
||||
profile.t4 = std::max(0.0, (d - s_min) / v);
|
||||
profile.t5 = t_j_a;
|
||||
profile.t6 = t_a;
|
||||
profile.t7 = t_j_a;
|
||||
profile.v_cruise = v;
|
||||
profile.a_limit = a;
|
||||
}
|
||||
|
||||
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
|
||||
profile.t5 + profile.t6 + profile.t7;
|
||||
}
|
||||
|
||||
double LgvSCurve::computeSegmentJerk(const LgvSCurveProfile& profile, double t) const
|
||||
{
|
||||
double j = profile.j_max * profile.direction;
|
||||
|
||||
// 判断所处阶段
|
||||
double t_end1 = profile.t1;
|
||||
double t_end2 = t_end1 + profile.t2;
|
||||
double t_end3 = t_end2 + profile.t3;
|
||||
double t_end4 = t_end3 + profile.t4;
|
||||
double t_end5 = t_end4 + profile.t5;
|
||||
double t_end6 = t_end5 + profile.t6;
|
||||
// double t_end7 = t_end6 + profile.t7; // = total_time
|
||||
|
||||
if (t < t_end1) {
|
||||
return j; // 段 1:正加加速度(加速)
|
||||
} else if (t < t_end2) {
|
||||
return 0.0; // 段 2:加加速度为 0(匀加速)
|
||||
} else if (t < t_end3) {
|
||||
return -j; // 段 3:负加加速度(减小加速度)
|
||||
} else if (t < t_end4) {
|
||||
return 0.0; // 段 4:加加速度为 0(巡航)
|
||||
} else if (t < t_end5) {
|
||||
return -j; // 段 5:负加加速度(开始减速)
|
||||
} else if (t < t_end6) {
|
||||
return 0.0; // 段 6:加加速度为 0(匀减速)
|
||||
} else {
|
||||
return j; // 段 7:正加加速度(减速结束)
|
||||
}
|
||||
}
|
||||
|
||||
double LgvSCurve::getPositionAtTime(const LgvSCurveProfile& profile, double t) const
|
||||
{
|
||||
if (t <= 0) return profile.p0;
|
||||
if (t >= profile.total_time) return profile.p0 + profile.distance * profile.direction;
|
||||
|
||||
double j = profile.j_max * profile.direction;
|
||||
double p = profile.p0;
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
// 时间边界
|
||||
double t_end1 = profile.t1;
|
||||
double t_end2 = t_end1 + profile.t2;
|
||||
double t_end3 = t_end2 + profile.t3;
|
||||
double t_end4 = t_end3 + profile.t4;
|
||||
double t_end5 = t_end4 + profile.t5;
|
||||
double t_end6 = t_end5 + profile.t6;
|
||||
|
||||
// 依次处理各阶段
|
||||
auto processSegment = [&](double dt, double jerk) {
|
||||
p += v * dt + 0.5 * a * dt * dt + (1.0/6.0) * jerk * dt * dt * dt;
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
// 段 1
|
||||
if (t <= t_end1) {
|
||||
processSegment(t, j);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t1, j);
|
||||
|
||||
// 段 2
|
||||
if (t <= t_end2) {
|
||||
processSegment(t - t_end1, 0.0);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t2, 0.0);
|
||||
|
||||
// 段 3
|
||||
if (t <= t_end3) {
|
||||
processSegment(t - t_end2, -j);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t3, -j);
|
||||
|
||||
// 段 4(巡航)
|
||||
if (t <= t_end4) {
|
||||
processSegment(t - t_end3, 0.0);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t4, 0.0);
|
||||
|
||||
// 段 5
|
||||
if (t <= t_end5) {
|
||||
processSegment(t - t_end4, -j);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t5, -j);
|
||||
|
||||
// 段 6
|
||||
if (t <= t_end6) {
|
||||
processSegment(t - t_end5, 0.0);
|
||||
return p;
|
||||
}
|
||||
processSegment(profile.t6, 0.0);
|
||||
|
||||
// 段 7
|
||||
processSegment(t - t_end6, j);
|
||||
return p;
|
||||
}
|
||||
|
||||
double LgvSCurve::getVelocityAtTime(const LgvSCurveProfile& profile, double t) const
|
||||
{
|
||||
if (t <= 0) return profile.v0;
|
||||
if (t >= profile.total_time) return profile.vf;
|
||||
|
||||
double j = profile.j_max * profile.direction;
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
// 时间边界
|
||||
double t_end1 = profile.t1;
|
||||
double t_end2 = t_end1 + profile.t2;
|
||||
double t_end3 = t_end2 + profile.t3;
|
||||
double t_end4 = t_end3 + profile.t4;
|
||||
double t_end5 = t_end4 + profile.t5;
|
||||
double t_end6 = t_end5 + profile.t6;
|
||||
|
||||
auto processSegment = [&](double dt, double jerk) {
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
if (t <= t_end1) {
|
||||
v += a * t + 0.5 * j * t * t;
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t1, j);
|
||||
|
||||
if (t <= t_end2) {
|
||||
v += a * (t - t_end1);
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t2, 0.0);
|
||||
|
||||
if (t <= t_end3) {
|
||||
double dt = t - t_end2;
|
||||
v += a * dt + 0.5 * (-j) * dt * dt;
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t3, -j);
|
||||
|
||||
if (t <= t_end4) {
|
||||
v += a * (t - t_end3);
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t4, 0.0);
|
||||
|
||||
if (t <= t_end5) {
|
||||
double dt = t - t_end4;
|
||||
v += a * dt + 0.5 * (-j) * dt * dt;
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t5, -j);
|
||||
|
||||
if (t <= t_end6) {
|
||||
v += a * (t - t_end5);
|
||||
return v;
|
||||
}
|
||||
processSegment(profile.t6, 0.0);
|
||||
|
||||
double dt = t - t_end6;
|
||||
v += a * dt + 0.5 * j * dt * dt;
|
||||
return v;
|
||||
}
|
||||
|
||||
double LgvSCurve::getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const
|
||||
{
|
||||
if (t <= 0 || t >= profile.total_time) return 0.0;
|
||||
|
||||
double j = profile.j_max * profile.direction;
|
||||
double a = profile.a0;
|
||||
|
||||
// 时间边界
|
||||
double t_end1 = profile.t1;
|
||||
double t_end2 = t_end1 + profile.t2;
|
||||
double t_end3 = t_end2 + profile.t3;
|
||||
double t_end4 = t_end3 + profile.t4;
|
||||
double t_end5 = t_end4 + profile.t5;
|
||||
double t_end6 = t_end5 + profile.t6;
|
||||
|
||||
if (t <= t_end1) {
|
||||
return a + j * t;
|
||||
}
|
||||
a += j * profile.t1;
|
||||
|
||||
if (t <= t_end2) {
|
||||
return a;
|
||||
}
|
||||
|
||||
if (t <= t_end3) {
|
||||
return a + (-j) * (t - t_end2);
|
||||
}
|
||||
a += (-j) * profile.t3;
|
||||
|
||||
if (t <= t_end4) {
|
||||
return a; // Should be ~0
|
||||
}
|
||||
|
||||
if (t <= t_end5) {
|
||||
return a + (-j) * (t - t_end4);
|
||||
}
|
||||
a += (-j) * profile.t5;
|
||||
|
||||
if (t <= t_end6) {
|
||||
return a;
|
||||
}
|
||||
|
||||
return a + j * (t - t_end6);
|
||||
}
|
||||
|
||||
double LgvSCurve::getJerkAtTime(const LgvSCurveProfile& profile, double t) const
|
||||
{
|
||||
if (t <= 0.0 || t >= profile.total_time) {
|
||||
return 0.0;
|
||||
}
|
||||
return computeSegmentJerk(profile, t);
|
||||
}
|
||||
|
||||
void LgvSCurve::generateTrajectory(const LgvSCurveProfile& profile, double dt,
|
||||
std::vector<double>& positions,
|
||||
std::vector<double>& velocities,
|
||||
std::vector<double>& accelerations) const
|
||||
{
|
||||
positions.clear();
|
||||
velocities.clear();
|
||||
accelerations.clear();
|
||||
|
||||
if (profile.total_time <= 0 || dt <= 0) {
|
||||
positions.push_back(profile.p0);
|
||||
velocities.push_back(profile.v0);
|
||||
accelerations.push_back(profile.a0);
|
||||
return;
|
||||
}
|
||||
|
||||
int num_points = static_cast<int>(std::ceil(profile.total_time / dt)) + 1;
|
||||
positions.reserve(num_points);
|
||||
velocities.reserve(num_points);
|
||||
accelerations.reserve(num_points);
|
||||
|
||||
for (double t = 0; t <= profile.total_time; t += dt) {
|
||||
positions.push_back(getPositionAtTime(profile, t));
|
||||
velocities.push_back(getVelocityAtTime(profile, t));
|
||||
accelerations.push_back(getAccelerationAtTime(profile, t));
|
||||
}
|
||||
|
||||
// 确保包含最终点
|
||||
if (positions.empty() ||
|
||||
std::abs(positions.back() - (profile.p0 + profile.distance * profile.direction)) > EPSILON) {
|
||||
positions.push_back(profile.p0 + profile.distance * profile.direction);
|
||||
velocities.push_back(profile.vf);
|
||||
accelerations.push_back(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
double LgvSCurve::getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return profile.v0;
|
||||
}
|
||||
|
||||
if (t <= 0.0) {
|
||||
return profile.v0;
|
||||
}
|
||||
if (t >= profile.total_time) {
|
||||
return profile.vf;
|
||||
}
|
||||
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
// seg1
|
||||
if (t <= profile.t1) {
|
||||
process_segment(t, profile.j1);
|
||||
return v;
|
||||
}
|
||||
process_segment(profile.t1, profile.j1);
|
||||
|
||||
// seg2
|
||||
const double t_after_1 = t - profile.t1;
|
||||
if (t_after_1 <= profile.t2) {
|
||||
process_segment(t_after_1, profile.j2);
|
||||
return v;
|
||||
}
|
||||
process_segment(profile.t2, profile.j2);
|
||||
|
||||
// seg3
|
||||
const double t_after_2 = t_after_1 - profile.t2;
|
||||
process_segment(t_after_2, profile.j3);
|
||||
return v;
|
||||
}
|
||||
|
||||
double LgvSCurve::getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return profile.a0;
|
||||
}
|
||||
|
||||
if (t <= 0.0) {
|
||||
return profile.a0;
|
||||
}
|
||||
if (t >= profile.total_time) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
// seg1
|
||||
if (t <= profile.t1) {
|
||||
process_segment(t, profile.j1);
|
||||
return a;
|
||||
}
|
||||
process_segment(profile.t1, profile.j1);
|
||||
|
||||
// seg2
|
||||
const double t_after_1 = t - profile.t1;
|
||||
if (t_after_1 <= profile.t2) {
|
||||
process_segment(t_after_1, profile.j2);
|
||||
return a;
|
||||
}
|
||||
process_segment(profile.t2, profile.j2);
|
||||
|
||||
// seg3
|
||||
const double t_after_2 = t_after_1 - profile.t2;
|
||||
process_segment(t_after_2, profile.j3);
|
||||
return a;
|
||||
}
|
||||
|
||||
double LgvSCurve::getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (t <= 0.0 || t >= profile.total_time) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (t <= profile.t1) {
|
||||
return profile.j1;
|
||||
}
|
||||
if (t <= profile.t1 + profile.t2) {
|
||||
return profile.j2;
|
||||
}
|
||||
return profile.j3;
|
||||
}
|
||||
|
||||
void LgvSCurve::integrateWholeProfile(const LgvSCurveVelocityProfile& profile,
|
||||
double& v_end,
|
||||
double& a_end) const
|
||||
{
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
process_segment(profile.t1, profile.j1);
|
||||
process_segment(profile.t2, profile.j2);
|
||||
process_segment(profile.t3, profile.j3);
|
||||
|
||||
v_end = v;
|
||||
a_end = a;
|
||||
}
|
||||
|
||||
bool LgvSCurve::isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<double> check_times;
|
||||
check_times.reserve(8);
|
||||
|
||||
check_times.push_back(0.0);
|
||||
check_times.push_back(profile.t1);
|
||||
check_times.push_back(profile.t1 + profile.t2);
|
||||
check_times.push_back(profile.total_time);
|
||||
|
||||
// seg1 内部若 acceleration 过零,则 velocity 可能在段内出现极值
|
||||
if (std::abs(profile.j1) > EPSILON && profile.t1 > EPSILON) {
|
||||
const double tz = -profile.a0 / profile.j1;
|
||||
if (tz > EPSILON && tz < profile.t1 - EPSILON) {
|
||||
check_times.push_back(tz);
|
||||
}
|
||||
}
|
||||
|
||||
for (double t : check_times) {
|
||||
const double v = getVelocityAtTime(profile, t);
|
||||
if (std::abs(v) > max_velocity_ + 1e-7) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
LgvSCurveVelocityProfile LgvSCurve::calculateVelocityProfile(double start_velocity,
|
||||
double end_velocity,
|
||||
double start_acceleration) const
|
||||
{
|
||||
LgvSCurveVelocityProfile best;
|
||||
best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_);
|
||||
best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_);
|
||||
best.vf = clamp(end_velocity, -max_velocity_, max_velocity_);
|
||||
|
||||
if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) {
|
||||
// 退化情况:这里不做特殊退化规划,直接返回 invalid
|
||||
return best;
|
||||
}
|
||||
|
||||
const double v0 = best.v0;
|
||||
const double a0 = best.a0;
|
||||
const double vf = best.vf;
|
||||
|
||||
// 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0”
|
||||
double s = sign(vf - v0);
|
||||
if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) {
|
||||
s = 1.0;
|
||||
}
|
||||
|
||||
const double dv = s * (vf - v0); // >= 0
|
||||
const double a0s = s * a0; // signed frame 下的初始 acceleration
|
||||
const double j = max_jerk_;
|
||||
const double amax = max_acceleration_;
|
||||
|
||||
auto normalize_nonnegative = [](double x) {
|
||||
return (x < 0.0 && x > -1e-10) ? 0.0 : x;
|
||||
};
|
||||
|
||||
auto try_candidate = [&](double t1, double t2, double t3,
|
||||
double j1s, double j2s, double j3s) {
|
||||
t1 = normalize_nonnegative(t1);
|
||||
t2 = normalize_nonnegative(t2);
|
||||
t3 = normalize_nonnegative(t3);
|
||||
|
||||
if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) {
|
||||
return;
|
||||
}
|
||||
|
||||
LgvSCurveVelocityProfile cand;
|
||||
cand.t1 = t1;
|
||||
cand.t2 = t2;
|
||||
cand.t3 = t3;
|
||||
cand.total_time = t1 + t2 + t3;
|
||||
|
||||
cand.j1 = s * j1s;
|
||||
cand.j2 = s * j2s;
|
||||
cand.j3 = s * j3s;
|
||||
|
||||
cand.v0 = v0;
|
||||
cand.a0 = a0;
|
||||
cand.vf = vf;
|
||||
cand.valid = true;
|
||||
|
||||
double vend = 0.0;
|
||||
double aend = 0.0;
|
||||
integrateWholeProfile(cand, vend, aend);
|
||||
|
||||
if (std::abs(vend - vf) > 1e-5) {
|
||||
return;
|
||||
}
|
||||
if (std::abs(aend) > 1e-5) {
|
||||
return;
|
||||
}
|
||||
if (!isVelocityLimitSatisfied(cand)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!best.valid || cand.total_time < best.total_time) {
|
||||
best = cand;
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------- UDU 三角形(无平台) ----------------
|
||||
{
|
||||
// Δv = (2A^2 - a0^2)/(2j)
|
||||
const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s);
|
||||
if (A2 >= -1e-10) {
|
||||
const double A = std::sqrt(std::max(0.0, A2));
|
||||
if (A <= amax + 1e-10 && A >= a0s - 1e-10) {
|
||||
const double t1 = (A - a0s) / j;
|
||||
const double t2 = 0.0;
|
||||
const double t3 = A / j;
|
||||
try_candidate(t1, t2, t3, +j, 0.0, -j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- UDU 梯形(有平台) ----------------
|
||||
{
|
||||
const double A = amax;
|
||||
if (A > EPSILON && A >= a0s - 1e-10) {
|
||||
const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j);
|
||||
const double t1 = (A - a0s) / j;
|
||||
const double t2 = (dv - base) / A;
|
||||
const double t3 = A / j;
|
||||
try_candidate(t1, t2, t3, +j, 0.0, -j);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- DUD 三角形(无平台) ----------------
|
||||
{
|
||||
// Δv = (a0^2 - 2B^2)/(2j)
|
||||
const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv);
|
||||
if (B2 >= -1e-10) {
|
||||
const double B = std::sqrt(std::max(0.0, B2));
|
||||
if (B <= amax + 1e-10 && B >= -a0s - 1e-10) {
|
||||
const double t1 = (a0s + B) / j;
|
||||
const double t2 = 0.0;
|
||||
const double t3 = B / j;
|
||||
try_candidate(t1, t2, t3, -j, 0.0, +j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- DUD 梯形(有平台) ----------------
|
||||
{
|
||||
const double B = amax;
|
||||
if (B > EPSILON && B >= -a0s - 1e-10) {
|
||||
const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j);
|
||||
const double t1 = (a0s + B) / j;
|
||||
const double t2 = (base - dv) / B;
|
||||
const double t3 = B / j;
|
||||
try_candidate(t1, t2, t3, -j, 0.0, +j);
|
||||
}
|
||||
}
|
||||
|
||||
// 已到终点附近
|
||||
if (!best.valid &&
|
||||
std::abs(vf - v0) <= VELOCITY_THRESHOLD &&
|
||||
std::abs(a0) <= ACCELERATION_THRESHOLD) {
|
||||
best.valid = false;
|
||||
best.total_time = 0.0;
|
||||
best.v0 = v0;
|
||||
best.a0 = a0;
|
||||
best.vf = vf;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
void LgvSCurve::generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt,
|
||||
std::vector<double>& velocities,
|
||||
std::vector<double>& accelerations,
|
||||
std::vector<double>& 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<int>(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
|
||||
@ -1,5 +1,6 @@
|
||||
add_library(motor_robot_arm SHARED
|
||||
src/motor_robot_arm.cpp
|
||||
src/speed_l_executor.cpp
|
||||
)
|
||||
|
||||
target_include_directories(motor_robot_arm PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
@ -8,10 +9,13 @@ target_link_libraries(motor_robot_arm
|
||||
PUBLIC
|
||||
cmvr_es::proto
|
||||
PRIVATE
|
||||
cmvr_es::algorithms::arm_motion
|
||||
cmvr_es::algorithms::lgv_arm_motion
|
||||
cmvr_es::ik_solver
|
||||
cmvr_es::algorithms::arm_control
|
||||
cmvr_es::joint_path_planner
|
||||
cmvr_es::joint_trajectory_smoother
|
||||
cmvr_es::collision_checker
|
||||
cmvr_es::device::motor_manager
|
||||
cmvr_es::device::ethercat_motor_driver
|
||||
cmvr_es::device::mujoco_motor_driver
|
||||
glog
|
||||
)
|
||||
@ -19,11 +23,24 @@ target_link_libraries(motor_robot_arm
|
||||
add_library(cmvr_es::device::motor_robot_arm ALIAS motor_robot_arm)
|
||||
install(TARGETS motor_robot_arm LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(speed_l_executor_test src/speed_l_executor_test.cpp)
|
||||
target_link_libraries(speed_l_executor_test PRIVATE
|
||||
cmvr_es::device::motor_robot_arm gtest gtest_main pthread)
|
||||
|
||||
add_executable(speedl_reversal_mujoco_test src/speedl_reversal_mujoco_test.cpp)
|
||||
target_link_libraries(speedl_reversal_mujoco_test PRIVATE
|
||||
cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager
|
||||
cmvr_es::device::mujoco_motor_driver cmvr_es::proto pthread)
|
||||
|
||||
add_executable(rrt_connect_mujoco_test src/rrt_connect_mujoco_test.cpp)
|
||||
target_compile_definitions(rrt_connect_mujoco_test PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(rrt_connect_mujoco_test PRIVATE
|
||||
cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager
|
||||
cmvr_es::ik_solver
|
||||
cmvr_es::mujoco_world cmvr_es::mujoco_viewer
|
||||
gtest gtest_main pthread)
|
||||
|
||||
add_executable(motor_robot_arm_mujoco_test
|
||||
src/motor_robot_arm_mujoco_test.cpp
|
||||
)
|
||||
|
||||
@ -1,12 +1,35 @@
|
||||
# speedL 连续换向与 MuJoCo 验证
|
||||
|
||||
触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。该模式下非同轴变向先停止再换轴;角速度仍使用原有策略。
|
||||
触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。非同轴转向使用三维速度过渡,保持速度与加速度连续,并检查整个过渡的速度、加速度、jerk 模长上界。非连续模式与角速度近反向时,仍先停稳再反向。
|
||||
|
||||
`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,保持原有的小角度方向跟随和低速换轴行为;接近及回撤设为 true。固定轴模式不适合方向不断变化的视觉对齐:小方向变化会累积到换轴阈值,导致反复停走。设为 false 也可用于与旧换向策略做同条件比较。运动中退出固定轴模式时会保留实际运动方向和加速度。
|
||||
`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,接近及回撤设为 true。两种模式的非同轴转向都使用受限向量过渡,不再直接转动速度方向或累积小角度后周期性停车。连续旋转的 Tool 目标可能存在跟随滞后;受限规划不承诺瞬时到达新方向。运动中切换模式保留实际速度和加速度。旧换向余弦阈值与切轴速度阈值配置已删除。
|
||||
|
||||
`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 仍可直接使用。控制线程将速度、加速度、jerk 作为同一命令读取。正常停止的收尾操作检查命令版本,避免清除之后提交的运动命令。
|
||||
`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 转发到这一入口。控制线程将速度、加速度、jerk 作为同一命令读取,新命令到达时原子更新限值和换向策略。运行中的新限值请求被拒绝时,执行器使用上一次有效参数提交一次零目标停止;恢复停止也失败才走直接零速收尾,并记录失败日志。`speedL()` 提交是异步的,周期线程里的拒绝通过日志报告。正常停止收尾和失败处理都检查命令版本,避免清除之后提交的运动命令。
|
||||
|
||||
机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置或无效的上限继续使用规划器默认值(线性 0.55/5/10,角向 1/5/12)。
|
||||
`SpeedLExecutor` 位于 `devices/arm/motor_robot_arm`,由 `MotorRobotArm` 创建和持有,随机械臂停止、关闭或析构结束周期线程;Task 通过机械臂的 `speedL` / `stopL` 接口使用它,不管理执行器生命周期。配置中的 `speed_l_controller.cartesian_velocity_controller` 字段继续保持兼容。
|
||||
|
||||
调用职责:`MotorRobotArm` 检查机械臂状态并提供电机读写;`SpeedLExecutor` 管理命令、控制周期和停止;`PinocchioCartesianVelocityPlanner` 将平滑后的末端速度映射为关节速度并做限位、偏差检查;`SCurvePlanner` 管理方向及 S 曲线运行状态,`SCurve` 只做数学计算。执行器统一处理周期和停止阈值的默认值。
|
||||
|
||||
笛卡尔规划接口位于 `algorithms/planner/cartesian/`:`cartesian_trajectory_planner.h` 定义 MoveL 接口,独立的 `cartesian_velocity_planner.h` 定义 speedL 在线接口,`cartesian_motion_planner_factory.h` 提供工厂。Pinocchio 实现在其 `pinocchio/` 子目录,`SCurvePlanner` 在其 `s_curve/` 子目录;数学核心 `SCurve` 留在 `curves/s_curve/`。关节路径规划另放在 `algorithms/planner/joint/`。类名、职责与调用方式保持不变,库和测试目标仍由 `algorithms/planner/CMakeLists.txt` 统一定义,构建输出位置保持不变。
|
||||
|
||||
```cpp
|
||||
#include "algorithms/planner/cartesian/cartesian_velocity_planner.h"
|
||||
#include "algorithms/planner/cartesian/cartesian_motion_planner_factory.h"
|
||||
```
|
||||
|
||||
执行器只依赖 `CartesianVelocityPlanner` 在线接口,MoveL 接口保留在现有 `CartesianTrajectoryPlanner` 中。新命令调用一次 `submit(target, options, frame)`,每拍调用 `step(dt, q, qd)`;两者均由控制线程串行调用。`CartesianVelocityStep` 一次返回状态、关节速度命令、平滑后的 Base 目标 twist 和按需捕获的参考;失败时命令为空、twist 为零、参考无效。目标 twist 是关节限幅前的笛卡尔规划目标,不是实测 TCP 速度。旧的限值更新、独立捕获和规划器缓存 getter 接口已删除。
|
||||
|
||||
`PinocchioCartesianTrajectoryPlanner` 只实现 MoveL;`PinocchioCartesianVelocityPlanner` 只实现 speedL,独立持有在线目标和 SCurvePlanner。两个接口互不继承,`CartesianMotionPlannerFactory::createMoveL()` 和 `createSpeedL()` 分别创建并配置对应实例。两者共享机械臂的运动学求解器,机械臂切换到 MoveL 前先停止并等待速度控制线程退出。现有 protobuf 字段名保持兼容。
|
||||
|
||||
`SCurvePlanner` 初始化后每周期调用 `plan(target, frame, dt, base_R_tool)`;零目标表示平滑停止,相同目标继续已有曲线。`getAccelerationBase()` 是最终命令的区间平均加速度,`getJerkBase()` 按相邻区间中心时间差分,支持周期变化。没有反馈同步或独立停止状态入口。机械臂急停由 `MotorRobotArm` 关闭执行器并调用电机 quick stop。
|
||||
|
||||
`SCurvePlanner` 的限值必须为有限数且大于 1e-9,周期必须至少为 1e-9 秒,重规划阈值必须为有限非负数;非法初始速度、目标、周期、坐标系或 Tool 旋转矩阵中的非有限数会在修改状态前抛出 `std::invalid_argument`。Pinocchio 适配层把错误转为配置失败或 `InvalidArgument`。protobuf 限值与阈值为零时保留默认值,负数和非有限值拒绝。初始化速度超过上限会拒绝,不能只截断内部标量。动态降低限值时,若当前速度、加速度已超过新上限,或无法验证后续曲线满足新上限,拒绝更新并保留完整旧状态;不直接截断当前速度、加速度。标量曲线计算无解或产生非有限结果时抛出 `std::runtime_error`,适配层返回 `CommandFailed`。方向过渡候选未通过时继续推进已经验证的原曲线,再尝试新目标,不会冻结当前非零加速度。
|
||||
|
||||
参考捕获使用首次成功 `step` 的 TCP 位姿,Tool 目标由规划器锁定为该拍的 Base 方向;后续周期不重新旋转这一已锁定目标。执行器只在电机发送成功且命令版本仍匹配时发布参考。未请求捕获的 Tool 目标仍随每拍 Tool 坐标系转换。发送回调只接收关节速度,不再传递已由规划器处理的加速度。
|
||||
|
||||
每个规划周期合并计算当前 TCP 位姿和 Jacobian,当前直线偏差检查复用该位姿。启用直线偏差检查且正在平移时,仍单独计算预测下一周期的 FK 并复检。执行器复用关节状态和输出缓冲区。
|
||||
|
||||
机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置的上限使用规划器默认值(线性 0.55/5/10,角向 1/5/12),非法数值明确拒绝。
|
||||
|
||||
例如机械臂配置加速度 5、jerk 10 时,回撤请求 60/60 实际按 5/10 规划,请求 3/6 则按 3/6 规划。任务参数不能提高机械臂上限。
|
||||
|
||||
@ -36,29 +59,33 @@ touch {
|
||||
|
||||
先 MoveJ 到已有运动测试姿态,然后调用 `speedL(vy=+0.08)`,运动过程中直接调用 `speedL(vy=-0.08)`。默认 Base 坐标系,`--tool-frame true` 可验证 Tool 坐标系。测量来自 MuJoCo `R_FINGER_TIP_SITE` 的位置和雅可比乘实际 qvel;不是规划速度的积分。
|
||||
|
||||
在仓库根目录运行(需要已配置 `cmake-build-debug`;可用 `CMVR_BUILD_DIR` 覆盖):
|
||||
在仓库根目录先完成构建和安装,再直接运行测试程序:
|
||||
|
||||
```bash
|
||||
./scripts/build.sh Debug
|
||||
export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
speedl_test="$PWD/build/Debug/cmvr-es/devices/arm/motor_robot_arm/speedl_reversal_mujoco_test"
|
||||
|
||||
# 匀速阶段换向:接近加速度 5,回撤加速度 3,jerk 均为 10。
|
||||
./script/test_speedl_reversal_mujoco.sh --csv /tmp/reversal-new.csv
|
||||
"$speedl_test" --csv /tmp/reversal-new.csv
|
||||
|
||||
# 同一新版本中选择旧换向策略,比较算法本身。
|
||||
./script/test_speedl_reversal_mujoco.sh --legacy true --csv /tmp/reversal-legacy.csv
|
||||
"$speedl_test" --legacy true --csv /tmp/reversal-legacy.csv
|
||||
|
||||
# 仍在加速时,命令 vy 首次达到 0.032 m/s 即反向。
|
||||
./script/test_speedl_reversal_mujoco.sh --trigger-speed 0.032 --csv /tmp/reversal-accelerating.csv
|
||||
"$speedl_test" --trigger-speed 0.032 --csv /tmp/reversal-accelerating.csv
|
||||
|
||||
# 上限仍为 10,回撤请求 60 将被限制为 10。
|
||||
./script/test_speedl_reversal_mujoco.sh --reverse-jerk 60 --reverse-acceleration 60 \
|
||||
"$speedl_test" --reverse-jerk 60 --reverse-acceleration 60 \
|
||||
--capture-reference true --csv /tmp/reversal-capped.csv
|
||||
|
||||
# 将仿真机械臂 jerk 上限设为 60;接近请求 10,回撤请求 60。
|
||||
./script/test_speedl_reversal_mujoco.sh --jerk 60 --approach-jerk 10 \
|
||||
"$speedl_test" --jerk 60 --approach-jerk 10 \
|
||||
--reverse-jerk 60 --capture-reference true \
|
||||
--csv /tmp/reversal-jerk60.csv
|
||||
|
||||
# Tool 坐标系和触屏任务使用的参数接口。
|
||||
./script/test_speedl_reversal_mujoco.sh --tool-frame true --jerk 60 --approach-jerk 10 --reverse-jerk 60 \
|
||||
"$speedl_test" --tool-frame true --jerk 60 --approach-jerk 10 --reverse-jerk 60 \
|
||||
--capture-reference true --csv /tmp/reversal-tool.csv
|
||||
```
|
||||
|
||||
@ -66,14 +93,16 @@ touch {
|
||||
|
||||
`max_forward_mm` 是反向调用前采样点之后,实际 TCP 沿前进轴的最大正位移;`peak_at_ms` 是到达该最远点的时间;`actual_reverse_ms` 要求至少连续 5 次采样的轴向速度小于 -0.0001 m/s;`return_to_origin_ms` 是确认反向后返回调用时位置的时间。Tool 模式的 CSV 速度字段也表示沿锁定前进轴的投影。
|
||||
|
||||
测试要求换向前实际速度为正、之后产生反向速度并退回起点,且控制器未提前退出;使用起点锁存时还要求参考有效。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。
|
||||
测试要求换向前实际速度为正、之后产生反向速度并退回起点,且执行器未提前退出;使用起点锁存时还要求参考有效。停止后要求执行器退出 busy、TCP 实测线速度低于 0.01 m/s,再依次执行 `moveL`、恢复 `speedL`、停止和 `moveJ`,验证模式切换。`MODE_SWITCH` 日志记录 MoveL 位置误差、恢复运动的实际位移和停止残速。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。
|
||||
|
||||
现有 `motor_robot_arm_mujoco_test` 默认打开可视化窗口;设置 `CMVR_MUJOCO_HEADLESS=1` 可在不创建窗口的情况下运行相同的 MoveJ、MoveL 和 speedL 仿真检查。
|
||||
|
||||
## 回归测试
|
||||
|
||||
构建并运行 `cartesian_twist_limiter_reversal_test`、`s_curve_velocity_planner_stop_test` 和 `cartesian_velocity_controller_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、普通停止、非同轴转向、负速度反馈、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。
|
||||
构建并运行 `s_curve_planner_reversal_test` 和 `speed_l_executor_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、重复零目标平滑停止、非同轴转向、负速度下切换策略、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。
|
||||
|
||||
`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、旧接口及停止、独立角加速度限幅和非法请求。测试不初始化电机。
|
||||
`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、仅指定加速度及停止、独立角加速度限幅和非法请求。另验证未提交命令及单步失败时不返回旧输出,以及 Tool 参考锁定后与 Base 目标的持续输出一致。测试不初始化电机。
|
||||
|
||||
对齐回归覆盖每 20 ms 小幅更新速度方向:显式关闭固定轴模式后,20 mm/s 的命令不会因方向变化反复降到零;同时验证对齐后启用连续换向仍能平滑过零,以及反向运动中退出固定轴模式不会翻转实际速度。
|
||||
对齐回归覆盖每 20 ms 小幅更新方向、单拍 0.01 rad 方向变化、持续旋转 Tool 目标和速度恰在上限的情况,直接对最终速度命令差分检查 a/j 模长,并验证没有周期性降零。另覆盖拒绝不兼容降限后未来轨迹不变、角限值失败不部分更新线限值,以及停止恢复只重试一次。同轴连续换向过零仍保留加速度。
|
||||
|
||||
运行时应优先加载当前构建的项目动态库,测试脚本已处理;不要把新可执行文件与 `output/lib` 的旧项目库混用。
|
||||
运行前应确认构建和安装成功,确保 `output/lib` 中的项目动态库与测试程序属于同一次构建。
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
#define CMVR_ES_MOTOR_ROBOT_ARM_H
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
@ -9,14 +10,19 @@
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#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<Result> 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<AbstractMotor> getMotor_(const std::string& joint_name) const;
|
||||
bool readArmState_(std::vector<double>& q_now, std::vector<double>& qd_now) const;
|
||||
std::vector<double> readJointPosition_() const;
|
||||
Result stopCartesianMotionAndWait_();
|
||||
Result waitForJointTarget_(const std::vector<double>& 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<Result(const std::vector<double>&, std::vector<double>&)>& resolve_goal);
|
||||
Result waitForJointTarget_(const std::vector<double>& target,
|
||||
const std::function<bool()>& is_cancelled = {},
|
||||
const std::string& command = "moveJ") const;
|
||||
|
||||
bool planRecoveryTrajectory_(const std::vector<double>& 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<double> moveLJointVelocityLimits_(const std::vector<double>& qd_max) const;
|
||||
static Result unsupported_(const std::string& name);
|
||||
@ -131,12 +163,16 @@ private:
|
||||
std::shared_ptr<MotorManager> motor_manager_{nullptr};
|
||||
|
||||
std::shared_ptr<cmvr::IKSolver> ik_solver_{nullptr};
|
||||
std::shared_ptr<JointMotionPlanner> joint_planner_{nullptr};
|
||||
std::shared_ptr<CartesianMotionPlanner> cartesian_planner_{nullptr};
|
||||
std::unique_ptr<CartesianVelocityController> cartesian_velocity_controller_{nullptr};
|
||||
std::shared_ptr<JointTrajectorySmoother> trajectory_smoother_;
|
||||
std::shared_ptr<cmvr::JointPathPlanner> joint_path_planner_;
|
||||
std::unique_ptr<cmvr::CollisionChecker> path_collision_checker_;
|
||||
double joint_trajectory_sample_period_s_{0.001};
|
||||
std::shared_ptr<CartesianTrajectoryPlanner> cartesian_planner_{nullptr};
|
||||
std::unique_ptr<SpeedLExecutor> speed_l_executor_{nullptr};
|
||||
|
||||
// MoveJ post-trajectory settling criteria. These defaults preserve the
|
||||
// Joint-motion position-limit tolerance and post-trajectory settling criteria. These defaults preserve the
|
||||
// historical behavior when the optional arm configuration fields are absent.
|
||||
double move_j_joint_limit_tolerance_rad_{1e-5};
|
||||
double move_j_settle_timeout_s_{2.0};
|
||||
double move_j_position_tolerance_rad_{2e-3};
|
||||
double move_j_velocity_tolerance_rad_s_{2e-2};
|
||||
@ -144,8 +180,8 @@ private:
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> busy_{false};
|
||||
std::atomic<bool> powered_on_{false};
|
||||
double speed_scaling_{1.0};
|
||||
std::atomic<std::uint64_t> joint_motion_stop_generation_{0};
|
||||
std::atomic<double> speed_scaling_{1.0};
|
||||
std::atomic<bool> protective_stopped_{false};
|
||||
std::atomic<bool> emergency_stopped_{false};
|
||||
std::atomic<bool> protective_recovery_active_{false};
|
||||
|
||||
119
cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h
Normal file
119
cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h
Normal file
@ -0,0 +1,119 @@
|
||||
#ifndef CMVR_ES_SPEED_L_EXECUTOR_H
|
||||
#define CMVR_ES_SPEED_L_EXECUTOR_H
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#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<bool(std::vector<double>& q, std::vector<double>& qd)>;
|
||||
using SendVelocityCallback = std::function<Result(const JointVelocityCommand& velocity)>;
|
||||
using ReadScalingCallback = std::function<double()>;
|
||||
// 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<double()>;
|
||||
using EndCycleCallback = std::function<void(bool finished)>;
|
||||
|
||||
SpeedLExecutor(Config config,
|
||||
std::shared_ptr<CartesianVelocityPlanner> 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<double> 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<double>& q, std::vector<double>& 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<double>& velocity);
|
||||
static double twistNorm_(const CartesianVelocity& velocity);
|
||||
|
||||
private:
|
||||
Config config_;
|
||||
std::shared_ptr<CartesianVelocityPlanner> 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<bool> 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<bool> busy_{false};
|
||||
std::atomic<bool> 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
|
||||
File diff suppressed because it is too large
Load Diff
@ -4,18 +4,27 @@
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <Eigen/Geometry>
|
||||
|
||||
#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<double>::infinity()};
|
||||
double move_l_error{std::numeric_limits<double>::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<MotorRobotArm>(arm_config);
|
||||
arm_ = std::make_unique<MotorRobotArm>(arm_config_);
|
||||
ASSERT_NO_THROW(arm_->init());
|
||||
}
|
||||
|
||||
@ -186,14 +194,35 @@ protected:
|
||||
std::shared_ptr<MotorManager> motor_system_;
|
||||
std::shared_ptr<simulate::MujocoWorld> world_;
|
||||
std::unique_ptr<MotorRobotArm> 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<MotorRobotArm>(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<MuJocoViewer> viewer;
|
||||
if (!headless) {
|
||||
viewer = std::make_unique<MuJocoViewer>(world_);
|
||||
viewer->setupCamera(2.5, -160.0, -25.0);
|
||||
}
|
||||
ScenarioOutcome outcome;
|
||||
|
||||
std::thread scenario([&] {
|
||||
@ -220,12 +249,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ)
|
||||
outcome.worker_error = error.what();
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
|
||||
viewer.requestStop();
|
||||
if (viewer) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
|
||||
viewer->requestStop();
|
||||
}
|
||||
});
|
||||
|
||||
viewer.setRunning(true);
|
||||
viewer.run();
|
||||
if (viewer) {
|
||||
viewer->setRunning(true);
|
||||
viewer->run();
|
||||
}
|
||||
scenario.join();
|
||||
|
||||
std::cout << "[MotorRobotArmMujocoTest] moveJ initial max error: "
|
||||
@ -236,12 +269,53 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ)
|
||||
EXPECT_LT(outcome.move_j_initial_error, 0.10);
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, MoveJWithoutKinematics)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
arm_.reset();
|
||||
arm_config_.clear_kinematics();
|
||||
arm_config_.clear_motion();
|
||||
arm_config_.mutable_motion()->mutable_move_j()->set_settle_timeout_s(2.0);
|
||||
arm_ = std::make_unique<MotorRobotArm>(arm_config_);
|
||||
if (!arm_->init() || arm_->kinematicsSolver() ||
|
||||
arm_->getRobotState().fault) {
|
||||
throw std::runtime_error("Joint-only arm initialization failed");
|
||||
}
|
||||
|
||||
auto target = arm_->getJointState().position;
|
||||
for (auto& q : target) q += 0.02;
|
||||
MotionOptions options;
|
||||
options.velocity = 0.2;
|
||||
options.acceleration = 0.5;
|
||||
options.jerk = 5.0;
|
||||
const auto result = arm_->moveJ(JointPositionCommand{target}, options);
|
||||
if (!result.ok()) throw std::runtime_error(result.message);
|
||||
std::cout << "Joint-only MoveJ max position error: "
|
||||
<< maxPositionError(arm_->getJointState().position, target) << std::endl;
|
||||
|
||||
target[0] = arm_->getRobotModel().joint_limits[0].upper + 0.1;
|
||||
if (arm_->moveJ(JointPositionCommand{target}, options).ok()) {
|
||||
throw std::runtime_error("MoveJ accepted a target outside the motor limits");
|
||||
}
|
||||
if (arm_->moveL(CartesianPose{}, options).ok() ||
|
||||
arm_->speedL(CartesianVelocity{}, 0.5, 0.1).ok()) {
|
||||
throw std::runtime_error("Unconfigured Cartesian motion was accepted");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, MoveL)
|
||||
{
|
||||
MotorRobotArm& arm = *arm_;
|
||||
const bool uses_qp = std::string(GetParam().name) == "QpIk";
|
||||
Result rejected_fast_move_l{Result::failure(ArmErrorCode::UnknownError, "not run")};
|
||||
double rejected_motion_m = std::numeric_limits<double>::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<MuJocoViewer> viewer;
|
||||
if (!headless) {
|
||||
viewer = std::make_unique<MuJocoViewer>(world_);
|
||||
viewer->setupCamera(2.5, -160.0, -25.0);
|
||||
}
|
||||
ScenarioOutcome outcome;
|
||||
|
||||
std::thread scenario([&] {
|
||||
@ -276,6 +350,14 @@ TEST_P(MotorRobotArmMujocoTest, MoveL)
|
||||
cartesian_options.acceleration = 20;
|
||||
cartesian_options.jerk = 100.0;
|
||||
|
||||
if (uses_qp) {
|
||||
// At 0.8 m/s, this path requires elbow velocity below -5 rad/s.
|
||||
// Hard Cartesian equality must reject it before execution.
|
||||
rejected_fast_move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base);
|
||||
rejected_motion_m = translationError(arm.getTcpPose(), move_l_start);
|
||||
cartesian_options.velocity = 0.2;
|
||||
}
|
||||
|
||||
std::cout << "[MotorRobotArmMujocoTest] moveL target pose" << std::endl;
|
||||
outcome.move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base);
|
||||
waitFor([&] {
|
||||
@ -286,12 +368,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveL)
|
||||
outcome.worker_error = error.what();
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
|
||||
viewer.requestStop();
|
||||
if (viewer) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
|
||||
viewer->requestStop();
|
||||
}
|
||||
});
|
||||
|
||||
viewer.setRunning(true);
|
||||
viewer.run();
|
||||
if (viewer) {
|
||||
viewer->setRunning(true);
|
||||
viewer->run();
|
||||
}
|
||||
scenario.join();
|
||||
|
||||
std::cout << "[MotorRobotArmMujocoTest] moveJ setup max error: "
|
||||
@ -301,75 +387,684 @@ TEST_P(MotorRobotArmMujocoTest, MoveL)
|
||||
EXPECT_TRUE(outcome.worker_error.empty()) << outcome.worker_error;
|
||||
EXPECT_TRUE(outcome.move_j_initial.ok()) << outcome.move_j_initial.message;
|
||||
EXPECT_LT(outcome.move_j_initial_error, 0.10);
|
||||
if (uses_qp) {
|
||||
std::cout << "[MotorRobotArmMujocoTest] rejected fast moveL: "
|
||||
<< rejected_fast_move_l.message << ", displacement_m=" << rejected_motion_m << std::endl;
|
||||
EXPECT_EQ(rejected_fast_move_l.code, ArmErrorCode::CommandFailed);
|
||||
EXPECT_LT(rejected_motion_m, 1e-6);
|
||||
EXPECT_LT(outcome.move_l_error, 0.0002);
|
||||
}
|
||||
EXPECT_TRUE(outcome.move_l.ok()) << outcome.move_l.message;
|
||||
EXPECT_LT(outcome.move_l_error, 0.04);
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, SpeedL)
|
||||
void MotorRobotArmMujocoTest::runSpeedL(const bool angular)
|
||||
{
|
||||
MotorRobotArm& arm = *arm_;
|
||||
const double speed = angular ? .1 : .05;
|
||||
const auto leg_duration = std::chrono::milliseconds(angular ? 3000 : 800);
|
||||
const char* label = angular ? "SpeedLRotation" : "SpeedL6D";
|
||||
|
||||
MuJocoViewer viewer(world_);
|
||||
viewer.setupCamera(2.5, -160.0, -25.0);
|
||||
ScenarioOutcome outcome;
|
||||
const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr;
|
||||
std::unique_ptr<MuJocoViewer> viewer;
|
||||
if (!headless) {
|
||||
viewer = std::make_unique<MuJocoViewer>(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<LegResult> legs;
|
||||
std::array<bool, 3> 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<double> 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<mjtNum> 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<std::mutex> 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<double> 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<double CartesianVelocity::*, 3> components = angular
|
||||
? std::array<double CartesianVelocity::*, 3>{&CartesianVelocity::wx, &CartesianVelocity::wy, &CartesianVelocity::wz}
|
||||
: std::array<double CartesianVelocity::*, 3>{&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<double, std::milli>(
|
||||
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<double> 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<std::vector<double>> invalid_targets{{}, std::vector<double>(kDof - 1),
|
||||
std::vector<double>(kDof + 1)};
|
||||
for (const double invalid : {std::numeric_limits<double>::quiet_NaN(),
|
||||
std::numeric_limits<double>::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<double> 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<double> 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<double> 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<std::mutex> 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<simulate::MujocoWorld> 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<double>::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<double>(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<double>(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<simulate::MujocoWorld> 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<double>::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<double, 6, 1> actual = Eigen::Matrix<double, 6, 1>::Zero();
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<mjtNum> 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<double, 6, 1> reported = (Eigen::Matrix<double, 6, 1>() << 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<std::shared_ptr<AbstractMotor>> 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<double>::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(
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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 <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <filesystem>
|
||||
#include <thread>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
struct FeedbackSample {
|
||||
double time_s, sim_time_s;
|
||||
std::vector<double> 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<FeedbackSample>& 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<double>::quiet_NaN();
|
||||
std::vector<double> 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<std::string> 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<simulate::MujocoWorldDevice>(world_config);
|
||||
ASSERT_TRUE(world_->init());
|
||||
// 只在仿真启动前设置初始姿态;规划后的运动通过机械臂接口执行。
|
||||
const std::vector<double> 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<MotorManager>(
|
||||
arm_config.motor().motor_system_id(), motors.motor(), "right_arm_mujoco_motors");
|
||||
ASSERT_TRUE(motors_->init());
|
||||
arm_ = std::make_shared<MotorRobotArm>(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<simulate::MujocoWorldDevice> world_;
|
||||
std::shared_ptr<MotorManager> motors_;
|
||||
std::shared_ptr<MotorRobotArm> arm_;
|
||||
std::shared_ptr<cmvr::IKSolver> 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<int> 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<double> joints; CartesianPose pose; };
|
||||
struct Profile { const char* name; double velocity, acceleration, jerk; };
|
||||
std::vector<Target> 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<Profile> 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<MuJocoViewer> viewer;
|
||||
if (!headless) {
|
||||
viewer = std::make_unique<MuJocoViewer>(world_->world());
|
||||
viewer->setupCamera(2.5, -160.0, -20.0);
|
||||
viewer->setRunning(true);
|
||||
}
|
||||
std::atomic<bool> 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<FeedbackSample> feedback;
|
||||
feedback.reserve(20000);
|
||||
std::atomic<bool> 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<std::mutex> lock(world_->world()->mutex());
|
||||
const auto* data = world_->world()->data();
|
||||
sample.time_s = std::chrono::duration<double>(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<double>(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<int>(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
|
||||
636
cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp
Normal file
636
cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp
Normal file
@ -0,0 +1,636 @@
|
||||
#include "devices/arm/motor_robot_arm/include/speed_l_executor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#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<CartesianVelocityPlanner> 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<bool>(begin_cycle_) != static_cast<bool>(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<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
std::lock_guard<std::mutex> 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<double>(duration));
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<double> 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<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
if (worker_.joinable()) {
|
||||
stop_requested_.store(true);
|
||||
cv_.notify_all();
|
||||
worker_.join();
|
||||
stop_requested_.store(false);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return shutdown_result_;
|
||||
}
|
||||
if (busy_.load()) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
finishing_ = true;
|
||||
}
|
||||
finishCommand_();
|
||||
}
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
recordFailureLocked_(result);
|
||||
}
|
||||
|
||||
Result SpeedLExecutor::clearFault_(const bool planning_only)
|
||||
{
|
||||
std::lock_guard<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
const auto explicit_recovery = [&] {
|
||||
return Result::failure(ArmErrorCode::RobotInFault,
|
||||
"speedL fault requires explicit recovery: " + last_result_.message);
|
||||
};
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
return last_result_;
|
||||
}
|
||||
|
||||
CartesianVelocity SpeedLExecutor::getCommandTwistBase() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return command_twist_snapshot_;
|
||||
}
|
||||
|
||||
SpeedLReference SpeedLExecutor::getReference() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return reference_;
|
||||
}
|
||||
|
||||
void SpeedLExecutor::workerLoop_()
|
||||
{
|
||||
using Clock = std::chrono::steady_clock;
|
||||
const auto period = std::chrono::duration_cast<Clock::duration>(
|
||||
std::chrono::duration<double>(config_.control_period_s));
|
||||
std::vector<double> q_now, qd_now;
|
||||
std::uint64_t submitted_version = 0, recovery_version = 0;
|
||||
std::optional<SpeedLOptions> accepted_options;
|
||||
std::optional<Clock::time_point> 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<std::mutex> 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<double>(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<double>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<double>(Clock::now() - *stop_started).count() >= config_.stop_timeout_s;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
cv_.wait_until(lock, deadline, [&] { return stop_requested_.load(); });
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
const auto error = callbackException("speedL worker");
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
recordFailureLocked_(error);
|
||||
}
|
||||
bool needs_stop;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<double>(config_.stop_timeout_s);
|
||||
std::vector<double> 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<double>(config_.control_period_s));
|
||||
}
|
||||
}
|
||||
|
||||
Result SpeedLExecutor::readState_(std::vector<double>& q, std::vector<double>& 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<double>& 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
|
||||
1031
cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp
Normal file
1031
cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp
Normal file
File diff suppressed because it is too large
Load Diff
@ -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<config::ArmRootConfig>(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();
|
||||
|
||||
@ -106,15 +106,32 @@ public:
|
||||
return speedL(velocity, options.acceleration, duration, frame);
|
||||
}
|
||||
virtual SpeedLReference getSpeedLReference() const { return {}; }
|
||||
// Submission success and the asynchronous execution result are distinct.
|
||||
virtual Result getSpeedLResult() const {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "speedL result is unavailable");
|
||||
}
|
||||
virtual Result stopMotion() = 0;
|
||||
|
||||
virtual Result moveP(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
FrameType frame = FrameType::Base)
|
||||
{
|
||||
if (options.is_tcp_pose_valid) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"MoveP TCP pose constraints are not supported by this robot arm");
|
||||
}
|
||||
return moveL(target, options, frame);
|
||||
}
|
||||
|
||||
// Plan to the exact joint configuration without converting through FK/IK.
|
||||
virtual Result moveP(const JointPositionCommand& target,
|
||||
const MotionOptions& options)
|
||||
{
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"joint-target MoveP is not supported by this robot arm");
|
||||
}
|
||||
|
||||
virtual Result startServoMode(const ServoOptions& options) = 0;
|
||||
virtual Result servoJ(const JointPositionCommand& target) = 0;
|
||||
virtual Result servoL(const CartesianPose& target,
|
||||
@ -132,44 +149,33 @@ public:
|
||||
virtual Result brakeRelease() = 0;
|
||||
virtual Result shutdown() = 0;
|
||||
virtual Result clearFault() = 0;
|
||||
// Only backends that can distinguish planning faults may recover them automatically.
|
||||
virtual Result recoverSpeedLPlanningFault() {
|
||||
return isFault()
|
||||
? Result::failure(ArmErrorCode::RobotInFault, "arm fault requires explicit recovery")
|
||||
: Result::success();
|
||||
}
|
||||
virtual Result unlockProtectiveStop() = 0;
|
||||
virtual Result loadProgram(const std::string& program_name) = 0;
|
||||
virtual Result playProgram() = 0;
|
||||
virtual Result pauseProgram() = 0;
|
||||
virtual Result stopProgram() = 0;
|
||||
|
||||
// Teaching and trajectory recording are optional vendor capabilities.
|
||||
// Drivers that do not explicitly override these methods report unsupported.
|
||||
virtual Result enterTeachingMode()
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"teaching mode is not supported by this robot arm");
|
||||
// Preserve optional vendor teaching capabilities from linbo_dev.
|
||||
virtual Result enterTeachingMode() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm");
|
||||
}
|
||||
virtual Result startTrajectoryRecording(const std::string& file_name)
|
||||
{
|
||||
(void)file_name;
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"trajectory recording is not supported by this robot arm");
|
||||
virtual Result startTrajectoryRecording(const std::string&) {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm");
|
||||
}
|
||||
virtual Result completeTeaching()
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"complete teaching is not supported by this robot arm");
|
||||
virtual Result completeTeaching() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "complete teaching is not supported by this robot arm");
|
||||
}
|
||||
virtual Result stopTrajectoryRecording()
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"trajectory recording is not supported by this robot arm");
|
||||
virtual Result stopTrajectoryRecording() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm");
|
||||
}
|
||||
virtual Result exitTeachingMode()
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"teaching mode is not supported by this robot arm");
|
||||
virtual Result exitTeachingMode() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm");
|
||||
}
|
||||
|
||||
virtual std::vector<double> ik(const std::string& base_link,
|
||||
|
||||
@ -5,18 +5,22 @@
|
||||
在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
./scripts/build.sh Debug
|
||||
export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
px6_test="$PWD/build/Debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_real_test"
|
||||
|
||||
# 每次读取都发起一个真实请求:检查串口应答耗时和按压力值。
|
||||
./script/test_px_6ax_gen3.sh --port /dev/ttyACM0 --module-id 2 \
|
||||
"$px6_test" --port /dev/ttyACM0 --module-id 2 \
|
||||
--mode sync --duration-s 30 --csv /tmp/paxini-sync.csv --raw-log /tmp/paxini-frames.log
|
||||
|
||||
# 与触屏任务相同:后台轮询,前台读取最新有效缓存。
|
||||
./script/test_px_6ax_gen3.sh --port /dev/ttyACM0 --module-id 2 \
|
||||
"$px6_test" --port /dev/ttyACM0 --module-id 2 \
|
||||
--mode stream --duration-s 30 --csv /tmp/paxini-stream.csv
|
||||
```
|
||||
|
||||
也可把 `--port` 指定为 `/dev/serial/by-id/` 下的稳定设备链接。设备端口取决于连接顺序;测试参数不会更改机器人部署配置里的串口。`module-id=2` 对应协议设备地址 3。
|
||||
|
||||
脚本会构建真实测试并优先加载本次构建的驱动和 protobuf。默认构建目录为 `cmake-build-debug`,可用 `CMVR_BUILD_DIR` 覆盖;构建目录须已完成 CMake 配置。串口应可读写,运行测试前退出占用同一串口的程序。
|
||||
先确认构建和安装成功,再运行测试,确保 `output/lib` 中的驱动和 protobuf 与测试程序属于同一次构建。串口应可读写,运行测试前退出占用同一串口的程序。
|
||||
|
||||
测试期间可用手轻按、松开传感器,终端每 100 ms 显示一次力值,CSV 记录每次 getter 调用。按 Ctrl-C 可结束。CSV 的无效读数留空,不能当作零力。进程在初始化失败、没有有效数据或存在读取失败时返回非零退出码。
|
||||
|
||||
|
||||
@ -77,7 +77,7 @@ TEST(TchlMotorRealTest, ProfilePosition)
|
||||
auto motor = initMotor(manager);
|
||||
motor->calibrateZeroQ();
|
||||
if (!motor->setMode(msgs::RUN_MODE_PROFILE_POSITION) || !motor->torqueOn() ||
|
||||
!motor->commandProfilePosition(-6, -1, kAccelerationRadS2)) {
|
||||
!motor->commandProfilePosition(3, -1, kAccelerationRadS2)) {
|
||||
throw std::runtime_error("Profile position command failed");
|
||||
}
|
||||
std::cout << "target=" << kTargetPositionRad << " rad" << std::endl;
|
||||
|
||||
13
cmvr-es/environment/CMakeLists.txt
Normal file
13
cmvr-es/environment/CMakeLists.txt
Normal file
@ -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)
|
||||
110
cmvr-es/environment/include/robot_model.h
Normal file
110
cmvr-es/environment/include/robot_model.h
Normal file
@ -0,0 +1,110 @@
|
||||
#ifndef CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H
|
||||
#define CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <pinocchio/multibody/fwd.hpp>
|
||||
#include <Eigen/Geometry>
|
||||
#include <coal/collision_object.h>
|
||||
|
||||
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<const CollisionShape> geometry;
|
||||
Eigen::Vector3d position{Eigen::Vector3d::Zero()};
|
||||
Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()};
|
||||
double bounding_radius_m{0.0};
|
||||
};
|
||||
|
||||
struct JointLimit {
|
||||
double lower{0.0};
|
||||
double upper{0.0};
|
||||
double max_velocity{0.0};
|
||||
double max_acceleration{0.0};
|
||||
double max_torque{0.0};
|
||||
};
|
||||
|
||||
// Device metadata remains usable without a URDF. Loaded model resources are
|
||||
// immutable and shared when this object is copied; live robot state is external.
|
||||
struct RobotModel {
|
||||
std::string name;
|
||||
// Preserve linbo_dev's vendor metadata alongside the shared model.
|
||||
std::string subtype;
|
||||
std::string description_id;
|
||||
std::string default_base_frame;
|
||||
std::string default_tcp_frame;
|
||||
bool detected_from_sdk{false};
|
||||
std::string manufacturer;
|
||||
std::string serial_number;
|
||||
std::size_t dof{0};
|
||||
std::vector<std::string> joint_names;
|
||||
std::vector<JointLimit> 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<CollisionBody> collisionBodies(
|
||||
const std::vector<double>& joint_positions,
|
||||
const std::vector<std::string>& 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<const pinocchio::Model> kinematics_;
|
||||
std::shared_ptr<const pinocchio::Model> collision_kinematics_;
|
||||
std::shared_ptr<const pinocchio::GeometryModel> collision_geometry_;
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
#endif // CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H
|
||||
310
cmvr-es/environment/src/robot_model.cpp
Normal file
310
cmvr-es/environment/src/robot_model.cpp
Normal file
@ -0,0 +1,310 @@
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include <pinocchio/algorithm/geometry.hpp>
|
||||
#include <pinocchio/algorithm/joint-configuration.hpp>
|
||||
#include <pinocchio/multibody/data.hpp>
|
||||
#include <pinocchio/multibody/geometry.hpp>
|
||||
#include <pinocchio/multibody/model.hpp>
|
||||
#include <pinocchio/parsers/urdf.hpp>
|
||||
|
||||
#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::Model>();
|
||||
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<JointLimit> limits;
|
||||
limits.reserve(names.size());
|
||||
std::unordered_set<std::string> 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<const pinocchio::Model> collision_kinematics = kinematics_;
|
||||
if (collision_path != urdf_path_) {
|
||||
auto model = std::make_shared<pinocchio::Model>();
|
||||
pinocchio::urdf::buildModel(collision_path, *model);
|
||||
requireMatchingKinematics(*kinematics_, *model);
|
||||
collision_kinematics = std::move(model);
|
||||
}
|
||||
auto geometry = std::make_shared<pinocchio::GeometryModel>();
|
||||
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<bool>(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<CollisionBody> RobotModel::collisionBodies(
|
||||
const std::vector<double>& joint_positions,
|
||||
const std::vector<std::string>& 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<pinocchio::JointIndex> 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<const pinocchio::Model> cached_model;
|
||||
thread_local std::shared_ptr<const pinocchio::GeometryModel> cached_geometry;
|
||||
thread_local std::unique_ptr<pinocchio::Data> data;
|
||||
thread_local std::unique_ptr<pinocchio::GeometryData> geometry_data;
|
||||
if (cached_model != collision_kinematics_) {
|
||||
data = std::make_unique<pinocchio::Data>(model);
|
||||
cached_model = collision_kinematics_;
|
||||
}
|
||||
if (cached_geometry != collision_geometry_) {
|
||||
geometry_data = std::make_unique<pinocchio::GeometryData>(geometry);
|
||||
cached_geometry = collision_geometry_;
|
||||
}
|
||||
pinocchio::updateGeometryPlacements(
|
||||
model, *data, geometry, *geometry_data, q);
|
||||
std::vector<CollisionBody> 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
|
||||
@ -2,6 +2,7 @@
|
||||
#define CMVR_ES_MUJOCO_WORLD_H
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
@ -46,6 +47,12 @@ public:
|
||||
bool isLoaded() const;
|
||||
bool isRunning() const;
|
||||
double timestep() const;
|
||||
// Pair one online control update with one physics step. The caller may
|
||||
// read feedback and submit commands between begin/end without a world lock.
|
||||
// finished=false submits this cycle; finished=true also unregisters the
|
||||
// controller and must be called on every exit, even between cycles.
|
||||
double beginControlCycle(const std::string& controller);
|
||||
void endControlCycle(const std::string& controller, bool finished);
|
||||
const std::string& lastError() const;
|
||||
const std::string& modelPath() const;
|
||||
|
||||
@ -54,8 +61,9 @@ public:
|
||||
|
||||
bool getJointPosition(const std::string& joint_name, double& position) const;
|
||||
bool getJointVelocity(const std::string& joint_name, double& velocity) const;
|
||||
bool getJointStates(const std::vector<std::string>& names,
|
||||
std::vector<double>& positions, std::vector<double>& velocities) const;
|
||||
bool getJointStates(const std::vector<std::string>& joint_names,
|
||||
std::vector<double>& positions,
|
||||
std::vector<double>& velocities) const;
|
||||
bool setJointPosition(const std::string& joint_name, double position);
|
||||
bool setJointVelocity(const std::string& joint_name, double velocity);
|
||||
bool setJointTargetPosition(const std::string& joint_name, double position);
|
||||
@ -68,7 +76,7 @@ public:
|
||||
const std::vector<double>& positions,
|
||||
const std::vector<double>& velocities);
|
||||
bool setJointTargetVelocity(const std::string& joint_name, double velocity);
|
||||
bool setJointTargetVelocities(const std::vector<std::string>& names,
|
||||
bool setJointTargetVelocities(const std::vector<std::string>& joint_names,
|
||||
const std::vector<double>& velocities);
|
||||
|
||||
mjModel* model();
|
||||
@ -114,6 +122,15 @@ private:
|
||||
void applyDirectControlLocked(double dt);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
struct ControlCycle {
|
||||
bool granted{false};
|
||||
bool acquired{false};
|
||||
bool submitted{false};
|
||||
};
|
||||
std::mutex control_mutex_;
|
||||
std::condition_variable control_cv_;
|
||||
std::unordered_map<std::string, ControlCycle> control_cycles_;
|
||||
bool control_window_open_{false};
|
||||
Options options_;
|
||||
mjModel* model_{nullptr};
|
||||
mjData* data_{nullptr};
|
||||
|
||||
@ -8,6 +8,7 @@
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
@ -167,11 +168,56 @@ bool MujocoWorld::start()
|
||||
|
||||
void MujocoWorld::stop()
|
||||
{
|
||||
stop_requested_.store(true);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(control_mutex_);
|
||||
stop_requested_.store(true);
|
||||
}
|
||||
control_cv_.notify_all();
|
||||
if (simulation_thread_.joinable()) {
|
||||
simulation_thread_.join();
|
||||
}
|
||||
running_.store(false);
|
||||
std::lock_guard<std::mutex> lock(control_mutex_);
|
||||
control_cycles_.clear();
|
||||
control_window_open_ = false;
|
||||
}
|
||||
|
||||
double MujocoWorld::beginControlCycle(const std::string& controller)
|
||||
{
|
||||
const double dt = timestep();
|
||||
std::unique_lock<std::mutex> 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<std::mutex> lock(control_mutex_);
|
||||
const auto it = control_cycles_.find(controller);
|
||||
if (it == control_cycles_.end()) return;
|
||||
if (finished) {
|
||||
control_cycles_.erase(it);
|
||||
} else if (it->second.acquired) {
|
||||
it->second.acquired = false;
|
||||
it->second.granted = false;
|
||||
it->second.submitted = true;
|
||||
}
|
||||
control_cv_.notify_all();
|
||||
}
|
||||
|
||||
void MujocoWorld::reset()
|
||||
@ -277,18 +323,24 @@ bool MujocoWorld::setJointPosition(const std::string& joint_name, const double p
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MujocoWorld::getJointStates(const std::vector<std::string>& names,
|
||||
std::vector<double>& positions, std::vector<double>& velocities) const
|
||||
bool MujocoWorld::getJointStates(const std::vector<std::string>& joint_names,
|
||||
std::vector<double>& positions,
|
||||
std::vector<double>& velocities) const
|
||||
{
|
||||
if (names.empty() || &positions == &velocities) return false;
|
||||
if (joint_names.empty() || &positions == &velocities) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<const JointHandle*> joints;
|
||||
for (const auto& name : names) {
|
||||
joints.reserve(joint_names.size());
|
||||
for (const auto& name : joint_names) {
|
||||
const JointHandle* joint = nullptr;
|
||||
if (!findJointLocked(name, joint) ||
|
||||
std::find(joints.begin(), joints.end(), joint) != joints.end() ||
|
||||
!std::isfinite(data_->qpos[joint->qpos_adr]) ||
|
||||
!std::isfinite(data_->qvel[joint->qvel_adr])) return false;
|
||||
!std::isfinite(data_->qvel[joint->qvel_adr])) {
|
||||
return false;
|
||||
}
|
||||
joints.push_back(joint);
|
||||
}
|
||||
positions.resize(joints.size());
|
||||
@ -300,28 +352,6 @@ bool MujocoWorld::getJointStates(const std::vector<std::string>& names,
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MujocoWorld::setJointTargetVelocities(const std::vector<std::string>& names,
|
||||
const std::vector<double>& velocities)
|
||||
{
|
||||
if (names.empty() || names.size() != velocities.size()) return false;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<JointHandle*> joints;
|
||||
for (std::size_t i = 0; i < names.size(); ++i) {
|
||||
JointHandle* joint = nullptr;
|
||||
if (!std::isfinite(velocities[i]) || !findJointLocked(names[i], joint) ||
|
||||
std::find(joints.begin(), joints.end(), joint) != joints.end()) return false;
|
||||
joints.push_back(joint);
|
||||
}
|
||||
// Validate all entries before changing any command.
|
||||
for (std::size_t i = 0; i < joints.size(); ++i) {
|
||||
auto* joint = joints[i];
|
||||
if (joint->mode != TargetMode::DirectVelocity) joint->position_reference = data_->qpos[joint->qpos_adr];
|
||||
joint->target_velocity = velocities[i];
|
||||
joint->mode = TargetMode::DirectVelocity;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MujocoWorld::setJointVelocity(const std::string& joint_name, const double velocity)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@ -455,6 +485,35 @@ bool MujocoWorld::setJointTargetVelocity(const std::string& joint_name, const do
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MujocoWorld::setJointTargetVelocities(const std::vector<std::string>& joint_names,
|
||||
const std::vector<double>& velocities)
|
||||
{
|
||||
if (joint_names.empty() || joint_names.size() != velocities.size()) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<JointHandle*> joints;
|
||||
joints.reserve(joint_names.size());
|
||||
for (std::size_t i = 0; i < joint_names.size(); ++i) {
|
||||
JointHandle* joint = nullptr;
|
||||
if (!std::isfinite(velocities[i]) || !findJointLocked(joint_names[i], joint) ||
|
||||
std::find(joints.begin(), joints.end(), joint) != joints.end()) {
|
||||
return false;
|
||||
}
|
||||
joints.push_back(joint);
|
||||
}
|
||||
// Validate the entire batch before changing any target or control mode.
|
||||
for (std::size_t i = 0; i < joints.size(); ++i) {
|
||||
auto* joint = joints[i];
|
||||
if (joint->mode != TargetMode::DirectVelocity) {
|
||||
joint->position_reference = data_->qpos[joint->qpos_adr];
|
||||
}
|
||||
joint->target_velocity = velocities[i];
|
||||
joint->mode = TargetMode::DirectVelocity;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
mjModel* MujocoWorld::model()
|
||||
{
|
||||
return model_;
|
||||
@ -666,6 +725,22 @@ void MujocoWorld::simulationLoop()
|
||||
|
||||
while (!stop_requested_.load()) {
|
||||
{
|
||||
std::unique_lock<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
if (model_ == nullptr || data_ == nullptr) {
|
||||
break;
|
||||
@ -685,6 +760,7 @@ void MujocoWorld::simulationLoop()
|
||||
|
||||
running_.store(false);
|
||||
CMVR_LOG(INFO) << "[MujocoWorld] simulation stopped";
|
||||
control_cv_.notify_all();
|
||||
}
|
||||
|
||||
void MujocoWorld::applyControlLocked()
|
||||
|
||||
17
dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake
vendored
Normal file
17
dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake
vendored
Normal file
@ -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)
|
||||
9
dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake
vendored
Normal file
9
dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake
vendored
Normal file
@ -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()
|
||||
233
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h
vendored
Normal file
233
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h
vendored
Normal file
@ -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 <utility>
|
||||
|
||||
#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<ompl::base::ConstrainedStateSpace>()->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<ConstrainedStateSpace>()->setSpaceInformation(this);
|
||||
setValidStateSamplerAllocator([](const SpaceInformation *si) -> std::shared_ptr<ValidStateSampler>
|
||||
{ return std::make_shared<ConstrainedValidStateSampler>(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<State *> &states,
|
||||
unsigned int /*count*/, bool endpoints, bool /*alloc*/) const override
|
||||
{
|
||||
bool success = stateSpace_->as<ConstrainedStateSpace>()->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<State *> &states,
|
||||
unsigned int /*count*/, bool /*endpoints*/, bool /*alloc*/) const override
|
||||
{
|
||||
auto &&atlas = stateSpace_->as<TangentBundleStateSpace>();
|
||||
|
||||
std::vector<State *> 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<AtlasStateSpace::StateType>();
|
||||
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<State *, double> &lastValid) const override
|
||||
{
|
||||
auto &&atlas = stateSpace_->as<TangentBundleStateSpace>();
|
||||
bool valid = motionValidator_->checkMotion(s1, s2, lastValid);
|
||||
|
||||
if (lastValid.first != nullptr)
|
||||
{
|
||||
auto astate = lastValid.first->as<AtlasStateSpace::StateType>();
|
||||
if (!atlas->project(astate))
|
||||
valid = false;
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
};
|
||||
} // namespace base
|
||||
} // namespace ompl
|
||||
|
||||
#endif
|
||||
325
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h
vendored
Normal file
325
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h
vendored
Normal file
@ -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 <Eigen/Core>
|
||||
#include <Eigen/Dense>
|
||||
#include <utility>
|
||||
|
||||
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<Eigen::VectorXd> 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<const Eigen::VectorXd> &x,
|
||||
Eigen::Ref<Eigen::VectorXd> 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<Eigen::MatrixXd> 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<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::MatrixXd> 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<Eigen::VectorXd> 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<const Eigen::VectorXd> &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<const Eigen::VectorXd> &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<ConstraintPtr> 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<ConstraintPtr> constraints)
|
||||
: Constraint(ambientDim, 0)
|
||||
{
|
||||
for (const auto &constraint : constraints)
|
||||
addConstraint(constraint);
|
||||
}
|
||||
|
||||
void function(const Eigen::Ref<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::VectorXd> 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<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::MatrixXd> 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<ConstraintPtr> 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
|
||||
70
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h
vendored
Normal file
70
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h
vendored
Normal file
@ -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 <iostream>
|
||||
|
||||
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
|
||||
78
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h
vendored
Normal file
78
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h
vendored
Normal file
@ -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<State *, double> &lastValid) const override;
|
||||
|
||||
private:
|
||||
StateSpace *stateSpace_;
|
||||
|
||||
void defaultSettings();
|
||||
};
|
||||
} // namespace base
|
||||
} // namespace ompl
|
||||
|
||||
#endif
|
||||
316
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h
vendored
Normal file
316
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h
vendored
Normal file
@ -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 <functional>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
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 <typename T>
|
||||
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: "<enum_val0>,<enum_val1>,<enum_val2>,..."
|
||||
- \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 <typename T>
|
||||
class SpecificParam : public GenericParam
|
||||
{
|
||||
public:
|
||||
/** \brief The type for the 'setter' function for this parameter */
|
||||
using SetterFn = std::function<void(T)>;
|
||||
|
||||
/** \brief The type for the 'getter' function for this parameter */
|
||||
using GetterFn = std::function<T()>;
|
||||
|
||||
/** \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<float>::getValue() const
|
||||
{
|
||||
return getter_ ? ompl::toString(getter_()) : "";
|
||||
}
|
||||
template <>
|
||||
inline std::string ompl::base::SpecificParam<double>::getValue() const
|
||||
{
|
||||
return getter_ ? ompl::toString(getter_()) : "";
|
||||
}
|
||||
template <>
|
||||
inline std::string ompl::base::SpecificParam<long double>::getValue() const
|
||||
{
|
||||
return getter_ ? ompl::toString(getter_()) : "";
|
||||
}
|
||||
template <>
|
||||
inline std::string ompl::base::SpecificParam<std::string>::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 <typename T>
|
||||
void declareParam(
|
||||
const std::string &name, const typename SpecificParam<T>::SetterFn &setter,
|
||||
const typename SpecificParam<T>::GetterFn &getter = [] { return T(); })
|
||||
{
|
||||
params_[name] = std::make_shared<SpecificParam<T>>(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<std::string, std::string> &kv, bool ignoreUnknown = false);
|
||||
|
||||
/** \brief Get the known parameter as a map from names to their values cast as string */
|
||||
void getParams(std::map<std::string, std::string> ¶ms) const;
|
||||
|
||||
/** \brief List the names of the known parameters */
|
||||
void getParamNames(std::vector<std::string> ¶ms) const;
|
||||
|
||||
/** \brief List the values of the known parameters, in the same order as getParamNames() */
|
||||
void getParamValues(std::vector<std::string> &vals) const;
|
||||
|
||||
/** \brief Get the map from parameter names to parameter descriptions */
|
||||
const std::map<std::string, GenericParamPtr> &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<std::string, GenericParamPtr> params_;
|
||||
};
|
||||
} // namespace base
|
||||
} // namespace ompl
|
||||
|
||||
#endif
|
||||
154
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h
vendored
Normal file
154
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h
vendored
Normal file
@ -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 <iostream>
|
||||
#include <boost/concept_check.hpp>
|
||||
#include <vector>
|
||||
|
||||
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 <class T>
|
||||
T *as()
|
||||
{
|
||||
/** \brief Make sure the type we are casting to is indeed a goal */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Goal *>));
|
||||
|
||||
return static_cast<T *>(this);
|
||||
}
|
||||
|
||||
/** \brief Cast this instance to a desired type. */
|
||||
template <class T>
|
||||
const T *as() const
|
||||
{
|
||||
/** \brief Make sure the type we are casting to is indeed a goal */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Goal *>));
|
||||
|
||||
return static_cast<const T *>(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
|
||||
70
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h
vendored
Normal file
70
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h
vendored
Normal file
@ -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
|
||||
144
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h
vendored
Normal file
144
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h
vendored
Normal file
@ -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 <utility>
|
||||
|
||||
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<State *, double> &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
|
||||
306
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h
vendored
Normal file
306
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h
vendored
Normal file
@ -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 <functional>
|
||||
#include <iostream>
|
||||
|
||||
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<Cost(const State *, const Goal *)>;
|
||||
|
||||
/// @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<Component> 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
|
||||
128
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h
vendored
Normal file
128
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h
vendored
Normal file
@ -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 <iostream>
|
||||
#include <boost/concept_check.hpp>
|
||||
#include <utility>
|
||||
|
||||
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 <class T>
|
||||
const T *as() const
|
||||
{
|
||||
/** \brief Make sure the type we are allocating is indeed a Path */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Path *>));
|
||||
|
||||
return static_cast<const T *>(this);
|
||||
}
|
||||
|
||||
/** \brief Cast this instance to a desired type. */
|
||||
template <class T>
|
||||
T *as()
|
||||
{
|
||||
/** \brief Make sure the type we are allocating is indeed a Path */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Path *>));
|
||||
|
||||
return static_cast<T *>(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
|
||||
432
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h
vendored
Normal file
432
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h
vendored
Normal file
@ -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 <functional>
|
||||
#include <boost/concept_check.hpp>
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
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 <class T>
|
||||
T *as()
|
||||
{
|
||||
/** \brief Make sure the type we are casting to is indeed a planner */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Planner *>));
|
||||
|
||||
return static_cast<T *>(this);
|
||||
}
|
||||
|
||||
/** \brief Cast this instance to a desired type. */
|
||||
template <class T>
|
||||
const T *as() const
|
||||
{
|
||||
/** \brief Make sure the type we are casting to is indeed a Planner */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, Planner *>));
|
||||
|
||||
return static_cast<const T *>(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<std::string()>;
|
||||
|
||||
/** \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<std::string, PlannerProgressProperty>;
|
||||
|
||||
/** \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 <typename T, typename PlannerType, typename SetterType, typename GetterType>
|
||||
void declareParam(const std::string &name, const PlannerType &planner, const SetterType &setter,
|
||||
const GetterType &getter, const std::string &rangeSuggestion = "")
|
||||
{
|
||||
params_.declareParam<T>(
|
||||
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 <typename T, typename PlannerType, typename SetterType>
|
||||
void declareParam(const std::string &name, const PlannerType &planner, const SetterType &setter,
|
||||
const std::string &rangeSuggestion = "")
|
||||
{
|
||||
params_.declareParam<T>(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<PlannerPtr(const SpaceInformationPtr &)>;
|
||||
} // namespace base
|
||||
} // namespace ompl
|
||||
|
||||
#endif
|
||||
437
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h
vendored
Normal file
437
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h
vendored
Normal file
@ -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 <iostream>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include "ompl/base/State.h"
|
||||
#include "ompl/base/Cost.h"
|
||||
#include "ompl/base/SpaceInformation.h"
|
||||
#include "ompl/util/ClassForward.h"
|
||||
#include <boost/serialization/access.hpp>
|
||||
|
||||
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 <class Archive>
|
||||
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 <class Archive>
|
||||
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<unsigned int> &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<unsigned int, const PlannerDataEdge *> &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<unsigned int> &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<unsigned int, const PlannerDataEdge *> &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<std::string, std::string> properties;
|
||||
|
||||
protected:
|
||||
/// \brief A mapping of states to vertex indexes. For fast lookup of vertex index.
|
||||
std::map<const State *, unsigned int> stateIndexMap_;
|
||||
/// \brief A mutable listing of the vertices marked as start states. Stored in sorted order.
|
||||
std::vector<unsigned int> startVertexIndices_;
|
||||
/// \brief A mutable listing of the vertices marked as goal states. Stored in sorted order.
|
||||
std::vector<unsigned int> 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<State *> 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
|
||||
94
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h
vendored
Normal file
94
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h
vendored
Normal file
@ -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 <boost/graph/adjacency_list.hpp>
|
||||
#include <boost/graph/graph_traits.hpp>
|
||||
|
||||
/// @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::vecS, boost::vecS, boost::bidirectionalS,
|
||||
boost::property<vertex_type_t, ompl::base::PlannerDataVertex *,
|
||||
boost::property<boost::vertex_index_t, unsigned int>>,
|
||||
boost::property<edge_type_t, ompl::base::PlannerDataEdge *,
|
||||
boost::property<boost::edge_weight_t, ompl::base::Cost>>>;
|
||||
/// @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<Type>::vertex_descriptor;
|
||||
/// \brief Boost.Graph edge descriptor
|
||||
using Edge = boost::graph_traits<Type>::edge_descriptor;
|
||||
/// \brief Boost.Graph vertex iterator
|
||||
using VIterator = boost::graph_traits<Type>::vertex_iterator;
|
||||
/// \brief Boost.Graph edge iterator
|
||||
using EIterator = boost::graph_traits<Type>::edge_iterator;
|
||||
/// \brief Boost.Graph input edge iterator
|
||||
using IEIterator = boost::graph_traits<Type>::in_edge_iterator;
|
||||
/// \brief Boost.Graph output edge iterator
|
||||
using OEIterator = boost::graph_traits<Type>::out_edge_iterator;
|
||||
/// \brief Boost.Graph adjacency iterator
|
||||
using AdjIterator = boost::graph_traits<Type>::adjacency_iterator;
|
||||
};
|
||||
|
||||
#endif
|
||||
294
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h
vendored
Normal file
294
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h
vendored
Normal file
@ -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 <boost/archive/binary_oarchive.hpp>
|
||||
#include <boost/archive/binary_iarchive.hpp>
|
||||
#include <boost/serialization/vector.hpp>
|
||||
#include <boost/serialization/utility.hpp>
|
||||
#include <fstream>
|
||||
|
||||
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 <boost/serialization/export.hpp>
|
||||
///
|
||||
/// class MyVertexClass : public ompl::base::PlannerDataVertex
|
||||
/// {
|
||||
/// // ---SNIP---
|
||||
///
|
||||
/// template <class Archive>
|
||||
/// void serialize(Archive & ar, const unsigned int version)
|
||||
/// {
|
||||
/// ar & boost::serialization::base_object<ompl::base::PlannerDataVertex>(*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<int> signature;
|
||||
|
||||
/// \brief boost::serialization routine
|
||||
template <typename Archive>
|
||||
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 <typename Archive>
|
||||
void serialize(Archive &ar, const unsigned int /*version*/)
|
||||
{
|
||||
ar & v_;
|
||||
ar & state_;
|
||||
ar & type_;
|
||||
}
|
||||
|
||||
const PlannerDataVertex *v_;
|
||||
std::vector<unsigned char> state_;
|
||||
VertexType type_;
|
||||
};
|
||||
|
||||
/// \brief The object containing all edge data that will be stored
|
||||
struct PlannerDataEdgeData
|
||||
{
|
||||
template <typename Archive>
|
||||
void serialize(Archive &ar, const unsigned int /*version*/)
|
||||
{
|
||||
ar & e_;
|
||||
ar & endpoints_;
|
||||
ar & weight_;
|
||||
}
|
||||
|
||||
const PlannerDataEdge *e_;
|
||||
std::pair<unsigned int, unsigned int> 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<State *> 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<PlannerDataVertex *>(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<unsigned char> 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<unsigned int> 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
|
||||
115
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h
vendored
Normal file
115
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h
vendored
Normal file
@ -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 <string>
|
||||
#include <ostream>
|
||||
|
||||
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
|
||||
136
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h
vendored
Normal file
136
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h
vendored
Normal file
@ -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 <functional>
|
||||
#include <memory>
|
||||
#include <ompl/base/ProblemDefinition.h>
|
||||
#include <ompl/util/Time.h>
|
||||
|
||||
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<bool()>;
|
||||
/** \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<PlannerTerminationConditionImpl> 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
|
||||
72
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h
vendored
Normal file
72
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h
vendored
Normal file
@ -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 <vector>
|
||||
|
||||
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<const State *> &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<const State *> &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<const State *> &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
|
||||
439
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h
vendored
Normal file
439
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h
vendored
Normal file
@ -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 <vector>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
|
||||
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<double>::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<void(const Planner *, const std::vector<const base::State *> &, 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<const State *> &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<double>::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<double>::epsilon());
|
||||
|
||||
/** \copydoc setStartAndGoalStates() */
|
||||
void setStartAndGoalStates(const ScopedState<> &start, const ScopedState<> &goal,
|
||||
const double threshold = std::numeric_limits<double>::epsilon())
|
||||
{
|
||||
setStartAndGoalStates(start.get(), goal.get(), threshold);
|
||||
}
|
||||
|
||||
/** \copydoc setGoalState() */
|
||||
void setGoalState(const ScopedState<> &goal,
|
||||
const double threshold = std::numeric_limits<double>::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<PlannerSolution> 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<State *> 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
|
||||
334
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h
vendored
Normal file
334
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h
vendored
Normal file
@ -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 <vector>
|
||||
#include <valarray>
|
||||
#include <iostream>
|
||||
#include <Eigen/Core>
|
||||
|
||||
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<double> &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<double> &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<Eigen::VectorXd> 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 R<sup>n</sup>. 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<Eigen::VectorXd> 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<double> &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<double> &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<Eigen::VectorXd> &projection,
|
||||
Eigen::Ref<Eigen::VectorXi> coord) const;
|
||||
|
||||
/** \brief Compute integer coordinates for a state */
|
||||
void computeCoordinates(const State *state, Eigen::Ref<Eigen::VectorXi> 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<Eigen::VectorXd> &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<double> 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<Eigen::VectorXd> 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
|
||||
553
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h
vendored
Normal file
553
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h
vendored
Normal file
@ -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 <boost/concept_check.hpp>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
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 T = StateSpace>
|
||||
class ScopedState
|
||||
{
|
||||
/** \brief Make sure the type we are allocating is indeed from a state space */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<T *, StateSpace *>));
|
||||
|
||||
/** \brief Make sure the type we are allocating is indeed a state */
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<typename T::StateType *, State *>));
|
||||
|
||||
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<StateType *>(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<StateType *>(s);
|
||||
}
|
||||
|
||||
/** \brief Copy constructor */
|
||||
ScopedState(const ScopedState<T> &other) : space_(other.getSpace())
|
||||
{
|
||||
State *s = space_->allocState();
|
||||
state_ = static_cast<StateType *>(s);
|
||||
space_->copyState(s, static_cast<const State *>(other.get()));
|
||||
}
|
||||
|
||||
/** \brief Copy constructor that allows instantiation from states of other type */
|
||||
template <class O>
|
||||
ScopedState(const ScopedState<O> &other) : space_(other.getSpace())
|
||||
{
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<O *, StateSpace *>));
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<typename O::StateType *, State *>));
|
||||
|
||||
// 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<StateType *>(s);
|
||||
space_->copyState(s, static_cast<const State *>(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<StateType *>(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<T> &operator=(const ScopedState<T> &other)
|
||||
{
|
||||
if (&other != this)
|
||||
{
|
||||
space_->freeState(state_);
|
||||
space_ = other.getSpace();
|
||||
|
||||
State *s = space_->allocState();
|
||||
state_ = static_cast<StateType *>(s);
|
||||
space_->copyState(s, static_cast<const State *>(other.get()));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** \brief Assignment operator */
|
||||
ScopedState<T> &operator=(const State *other)
|
||||
{
|
||||
if (other != static_cast<State *>(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 *>(state_), other);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** \brief Assignment operator */
|
||||
ScopedState<T> &operator=(const State &other)
|
||||
{
|
||||
if (&other != static_cast<State *>(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 *>(state_), &other);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** \brief Assignment operator that allows conversion of states */
|
||||
template <class O>
|
||||
ScopedState<T> &operator=(const ScopedState<O> &other)
|
||||
{
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<O *, StateSpace *>));
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<typename O::StateType *, State *>));
|
||||
|
||||
// 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<const void *>(&other) != reinterpret_cast<const void *>(this))
|
||||
{
|
||||
space_->freeState(state_);
|
||||
space_ = other.getSpace();
|
||||
|
||||
State *s = space_->allocState();
|
||||
state_ = static_cast<StateType *>(s);
|
||||
space_->copyState(s, static_cast<const State *>(other.get()));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** \brief Partial assignment operator. Only sets the double values of the state to specified real values */
|
||||
ScopedState<T> &operator=(const std::vector<double> &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<T> &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 <class O>
|
||||
bool operator==(const ScopedState<O> &other) const
|
||||
{
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<O *, StateSpace *>));
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<typename O::StateType *, State *>));
|
||||
|
||||
// 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<const State *>(state_), static_cast<const State *>(other.get()));
|
||||
}
|
||||
|
||||
/** \brief Checks equality of two states */
|
||||
template <class O>
|
||||
bool operator!=(const ScopedState<O> &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 index<sup>th</sup> 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 index<sup>th</sup> 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<std::string, StateSpace::ValueLocation> &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<std::string, StateSpace::ValueLocation> &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 <class O>
|
||||
double distance(const ScopedState<O> &other) const
|
||||
{
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<O *, StateSpace *>));
|
||||
BOOST_CONCEPT_ASSERT((boost::Convertible<typename O::StateType *, State *>));
|
||||
return distance(other.get());
|
||||
}
|
||||
|
||||
/** \brief Compute the distance to another state. */
|
||||
double distance(const State *state) const
|
||||
{
|
||||
return space_->distance(static_cast<const State *>(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<double> reals() const
|
||||
{
|
||||
std::vector<double> 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 <class T>
|
||||
inline std::ostream &operator<<(std::ostream &out, const ScopedState<T> &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 <class T, class Y>
|
||||
inline ScopedState<T> &operator<<(ScopedState<T> &to, const ScopedState<Y> &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 <class T, class Y>
|
||||
inline const ScopedState<T> &operator>>(const ScopedState<T> &from, ScopedState<Y> &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 <class T, class Y>
|
||||
inline const ScopedState<> operator^(const ScopedState<T> &a, const ScopedState<Y> &b)
|
||||
{
|
||||
ScopedState<> r(a.getSpace() + b.getSpace());
|
||||
return r << a << b;
|
||||
}
|
||||
|
||||
/** @} */
|
||||
|
||||
template <class T>
|
||||
const ScopedState<> ScopedState<T>::operator[](const StateSpacePtr &s) const
|
||||
{
|
||||
ScopedState<> r(s);
|
||||
return r << *this;
|
||||
}
|
||||
|
||||
/** \brief Shared pointer to a ScopedState<> */
|
||||
using ScopedStatePtr = std::shared_ptr<ScopedState<>>;
|
||||
} // namespace base
|
||||
} // namespace ompl
|
||||
|
||||
#endif
|
||||
73
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h
vendored
Normal file
73
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h
vendored
Normal file
@ -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 <utility>
|
||||
|
||||
#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
|
||||
459
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h
vendored
Normal file
459
dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h
vendored
Normal file
@ -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 <functional>
|
||||
#include <utility>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
/** \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<bool(const State *)>;
|
||||
|
||||
/** \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<State *> &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<State *> &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<State *> &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<State *, double> &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<State *> &states, unsigned int count,
|
||||
unsigned int &firstInvalidStateIndex) const;
|
||||
|
||||
/** \brief Check if a sequence of states is valid using subdivision. */
|
||||
bool checkMotion(const std::vector<State *> &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<State *> &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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user