Compare commits
4 Commits
ed9df8fd31
...
8656f3fae8
| Author | SHA1 | Date | |
|---|---|---|---|
| 8656f3fae8 | |||
| 1e3466c1e6 | |||
| 0813cad96c | |||
| 37a62fb3e3 |
42
README.md
42
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,6 +126,26 @@ 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
|
||||
|
||||
@ -69,7 +69,7 @@ function(setup_external_libs ARCH)
|
||||
set(HAS_LIB TRUE)
|
||||
|
||||
# Collect shared libs for install: *.so and *.so.*
|
||||
file(GLOB _SO_FILES
|
||||
file(GLOB _SO_FILES CONFIGURE_DEPENDS
|
||||
"${FULL_PATH}/lib/*.so"
|
||||
"${FULL_PATH}/lib/*.so.*"
|
||||
)
|
||||
@ -91,7 +91,7 @@ function(setup_external_libs ARCH)
|
||||
set(HAS_LIB TRUE)
|
||||
|
||||
# Only install Linux shared libs from base dir
|
||||
file(GLOB _SO_FILES2
|
||||
file(GLOB _SO_FILES2 CONFIGURE_DEPENDS
|
||||
"${FULL_PATH}/*.so"
|
||||
"${FULL_PATH}/*.so.*"
|
||||
)
|
||||
|
||||
@ -1,11 +1,15 @@
|
||||
add_subdirectory(curves)
|
||||
|
||||
add_subdirectory(common/base/logging)
|
||||
link_libraries(cmvr_es::logging)
|
||||
|
||||
add_subdirectory(environment)
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(hardware)
|
||||
add_subdirectory(algorithms)
|
||||
add_subdirectory(simulate)
|
||||
add_subdirectory(devices)
|
||||
add_subdirectory(safety)
|
||||
add_subdirectory(manager/device_manager)
|
||||
add_subdirectory(manager/media_source_hub)
|
||||
add_subdirectory(service/quic_edge)
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
add_subdirectory(motion_planner)
|
||||
add_subdirectory(planner)
|
||||
add_subdirectory(smoother)
|
||||
add_subdirectory(kinematics/ik_solver)
|
||||
add_subdirectory(perception)
|
||||
add_subdirectory(controllers)
|
||||
|
||||
@ -1,48 +1,45 @@
|
||||
add_library(self_collision_checker SHARED
|
||||
self_collision/src/self_collision_checker.cpp
|
||||
self_collision/src/distance_sampling_policy.cpp
|
||||
add_library(collision_checker SHARED
|
||||
src/collision_checker.cpp
|
||||
src/distance_sampling_policy.cpp
|
||||
)
|
||||
|
||||
target_include_directories(self_collision_checker PUBLIC
|
||||
target_include_directories(collision_checker PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
target_compile_definitions(self_collision_checker PRIVATE
|
||||
PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION
|
||||
PINOCCHIO_WITH_HPP_FCL
|
||||
target_compile_definitions(collision_checker PRIVATE
|
||||
COAL_DISABLE_HPP_FCL_WARNINGS
|
||||
)
|
||||
|
||||
target_link_libraries(self_collision_checker PUBLIC
|
||||
pinocchio_default
|
||||
pinocchio_parsers
|
||||
pinocchio_collision
|
||||
coal
|
||||
target_link_libraries(collision_checker PUBLIC
|
||||
cmvr_es::environment
|
||||
cmvr_es::proto
|
||||
)
|
||||
target_link_libraries(collision_checker PRIVATE coal)
|
||||
|
||||
add_library(cmvr_es::self_collision_checker ALIAS self_collision_checker)
|
||||
add_library(cmvr_es::collision_checker ALIAS collision_checker)
|
||||
|
||||
add_executable(self_collision_checker_test
|
||||
self_collision/test/self_collision_checker_test.cpp
|
||||
add_executable(collision_checker_test
|
||||
test/collision_checker_test.cpp
|
||||
)
|
||||
target_link_libraries(self_collision_checker_test PRIVATE
|
||||
cmvr_es::self_collision_checker
|
||||
target_link_libraries(collision_checker_test PRIVATE
|
||||
cmvr_es::collision_checker
|
||||
gtest
|
||||
gtest_main
|
||||
pthread
|
||||
)
|
||||
target_compile_definitions(self_collision_checker_test PRIVATE
|
||||
target_compile_definitions(collision_checker_test PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
|
||||
)
|
||||
|
||||
add_executable(self_collision_benchmark
|
||||
self_collision/benchmark/self_collision_benchmark.cpp
|
||||
benchmark/collision_benchmark.cpp
|
||||
)
|
||||
target_link_libraries(self_collision_benchmark PRIVATE
|
||||
cmvr_es::self_collision_checker
|
||||
cmvr_es::collision_checker
|
||||
)
|
||||
target_compile_definitions(self_collision_benchmark PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
|
||||
)
|
||||
|
||||
install(TARGETS self_collision_checker LIBRARY DESTINATION lib)
|
||||
install(TARGETS collision_checker LIBRARY DESTINATION lib)
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
|
||||
#include "algorithms/collision_detection/include/collision_checker.h"
|
||||
|
||||
int main()
|
||||
{
|
||||
@ -15,7 +15,7 @@ int main()
|
||||
"R_WRIST_P", "R_WRIST_Y", "R_WRIST_R",
|
||||
};
|
||||
|
||||
cmvr::SelfCollisionChecker checker;
|
||||
cmvr::CollisionChecker checker;
|
||||
std::string error;
|
||||
if (!checker.init(urdf_path, joint_names, {}, &error)) {
|
||||
std::cerr << "Initialization failed: " << error << '\n';
|
||||
@ -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
|
||||
@ -3,8 +3,9 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
@ -20,22 +21,22 @@ public:
|
||||
bool configure(const DistanceSamplingOptions& options,
|
||||
std::string* error = nullptr);
|
||||
|
||||
bool shouldCheck(const CollisionGeometrySnapshot& current,
|
||||
bool shouldCheck(const std::vector<CollisionBody>& current,
|
||||
Clock::time_point now) const;
|
||||
|
||||
void markChecked(const CollisionGeometrySnapshot& current,
|
||||
void markChecked(const std::vector<CollisionBody>& current,
|
||||
Clock::time_point now);
|
||||
|
||||
void reset();
|
||||
|
||||
double displacementSinceLastCheck(
|
||||
const CollisionGeometrySnapshot& current) const;
|
||||
const std::vector<CollisionBody>& current) const;
|
||||
|
||||
bool hasBaseline() const { return has_baseline_; }
|
||||
|
||||
private:
|
||||
DistanceSamplingOptions options_{};
|
||||
CollisionGeometrySnapshot last_checked_{};
|
||||
std::vector<CollisionBody> last_checked_{};
|
||||
Clock::time_point last_check_time_{};
|
||||
bool configured_{false};
|
||||
bool has_baseline_{false};
|
||||
@ -1,82 +0,0 @@
|
||||
#ifndef CMVR_ES_SELF_COLLISION_CHECKER_H
|
||||
#define CMVR_ES_SELF_COLLISION_CHECKER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Geometry>
|
||||
|
||||
namespace cmvr {
|
||||
|
||||
struct CollisionPair {
|
||||
std::string first;
|
||||
std::string second;
|
||||
};
|
||||
|
||||
struct SelfCollisionOptions {
|
||||
std::vector<CollisionPair> ignored_pairs;
|
||||
};
|
||||
|
||||
struct CollisionObjectPose {
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
|
||||
std::size_t geometry_index{0};
|
||||
Eigen::Vector3d position{Eigen::Vector3d::Zero()};
|
||||
Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()};
|
||||
double bounding_radius_m{0.0};
|
||||
};
|
||||
|
||||
struct CollisionGeometrySnapshot {
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
|
||||
std::vector<CollisionObjectPose, Eigen::aligned_allocator<CollisionObjectPose>> objects;
|
||||
};
|
||||
|
||||
struct SelfCollisionResult {
|
||||
bool valid{false};
|
||||
bool in_collision{false};
|
||||
double minimum_distance_m{0.0};
|
||||
std::string first;
|
||||
std::string second;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
// Instances cache Pinocchio work data and are not thread-safe.
|
||||
class SelfCollisionChecker {
|
||||
public:
|
||||
SelfCollisionChecker();
|
||||
~SelfCollisionChecker();
|
||||
|
||||
SelfCollisionChecker(SelfCollisionChecker&&) noexcept;
|
||||
SelfCollisionChecker& operator=(SelfCollisionChecker&&) noexcept;
|
||||
|
||||
SelfCollisionChecker(const SelfCollisionChecker&) = delete;
|
||||
SelfCollisionChecker& operator=(const SelfCollisionChecker&) = delete;
|
||||
|
||||
bool init(const std::string& urdf_path,
|
||||
const std::vector<std::string>& active_joint_names,
|
||||
const SelfCollisionOptions& options,
|
||||
std::string* error = nullptr);
|
||||
|
||||
bool makeSnapshot(const std::vector<double>& joint_positions,
|
||||
CollisionGeometrySnapshot* snapshot,
|
||||
std::string* error = nullptr);
|
||||
|
||||
SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot);
|
||||
SelfCollisionResult check(const std::vector<double>& joint_positions);
|
||||
|
||||
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_SELF_COLLISION_CHECKER_H
|
||||
@ -1,403 +0,0 @@
|
||||
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include <pinocchio/algorithm/geometry.hpp>
|
||||
#include <pinocchio/algorithm/joint-configuration.hpp>
|
||||
#include <pinocchio/collision/distance.hpp>
|
||||
#include <pinocchio/multibody/data.hpp>
|
||||
#include <pinocchio/multibody/geometry.hpp>
|
||||
#include <pinocchio/multibody/model.hpp>
|
||||
#include <pinocchio/parsers/urdf.hpp>
|
||||
|
||||
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 SelfCollisionChecker::Impl {
|
||||
public:
|
||||
bool init(const std::string& urdf_path,
|
||||
const std::vector<std::string>& active_joint_names,
|
||||
const SelfCollisionOptions& options,
|
||||
std::string* error)
|
||||
{
|
||||
reset();
|
||||
if (urdf_path.empty()) {
|
||||
setError(error, "URDF path is empty");
|
||||
return false;
|
||||
}
|
||||
if (!std::filesystem::is_regular_file(urdf_path)) {
|
||||
setError(error, "URDF file does not exist: " + urdf_path);
|
||||
return false;
|
||||
}
|
||||
if (active_joint_names.empty()) {
|
||||
setError(error, "Active joint list is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
pinocchio::urdf::buildModel(urdf_path, model_);
|
||||
pinocchio::urdf::buildGeom(
|
||||
model_, urdf_path, pinocchio::COLLISION, geometry_model_);
|
||||
} catch (const std::exception& exception) {
|
||||
setError(error, "Failed to load collision URDF: " + std::string(exception.what()));
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (geometry_model_.ngeoms == 0) {
|
||||
setError(error, "URDF contains no collision geometry: " + urdf_path);
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
std::unordered_set<pinocchio::JointIndex> active_joint_ids;
|
||||
std::unordered_set<std::string> unique_joint_names;
|
||||
joint_names_.reserve(active_joint_names.size());
|
||||
joint_q_indices_.reserve(active_joint_names.size());
|
||||
for (const auto& joint_name : active_joint_names) {
|
||||
if (joint_name.empty() || !unique_joint_names.insert(joint_name).second) {
|
||||
setError(error, "Active joint names must be non-empty and unique");
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
if (!model_.existJointName(joint_name)) {
|
||||
setError(error, "Joint not found in URDF: " + joint_name);
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
const pinocchio::JointIndex joint_id = model_.getJointId(joint_name);
|
||||
const auto& joint = model_.joints[joint_id];
|
||||
if (joint.nq() != 1) {
|
||||
setError(error, "Only one-DoF active joints are supported: " + joint_name);
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
active_joint_ids.insert(joint_id);
|
||||
joint_names_.push_back(joint_name);
|
||||
joint_q_indices_.push_back(joint.idx_q());
|
||||
}
|
||||
|
||||
geometry_link_names_.resize(geometry_model_.ngeoms);
|
||||
std::unordered_set<std::string> selected_link_names;
|
||||
for (pinocchio::GeomIndex geometry_id = 0;
|
||||
geometry_id < geometry_model_.ngeoms;
|
||||
++geometry_id) {
|
||||
auto& geometry = geometry_model_.geometryObjects[geometry_id];
|
||||
const std::string link_name = geometry.parentFrame < model_.frames.size()
|
||||
? model_.frames[geometry.parentFrame].name
|
||||
: geometry.name;
|
||||
geometry_link_names_[geometry_id] = link_name;
|
||||
|
||||
const bool is_static = geometry.parentJoint == 0;
|
||||
const bool belongs_to_active_arm = active_joint_ids.count(geometry.parentJoint) != 0;
|
||||
if (!is_static && !belongs_to_active_arm) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!geometry.geometry) {
|
||||
setError(error, "Collision geometry is null for link: " + link_name);
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
geometry.geometry->computeLocalAABB();
|
||||
selected_geometry_indices_.push_back(geometry_id);
|
||||
selected_link_names.insert(link_name);
|
||||
}
|
||||
|
||||
if (selected_geometry_indices_.size() < 2) {
|
||||
setError(error, "Fewer than two collision geometries remain after arm filtering");
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
std::set<LinkPairKey> ignored_pairs;
|
||||
for (const auto& pair : options.ignored_pairs) {
|
||||
if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) {
|
||||
setError(error, "Ignored collision pairs require two different non-empty links");
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) {
|
||||
setError(error,
|
||||
"Ignored collision pair references an inactive or unknown link: " +
|
||||
pair.first + ", " + pair.second);
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
ignored_pairs.insert(canonicalPair(pair.first, pair.second));
|
||||
}
|
||||
|
||||
geometry_model_.removeAllCollisionPairs();
|
||||
for (std::size_t first_index = 0;
|
||||
first_index < selected_geometry_indices_.size();
|
||||
++first_index) {
|
||||
const auto first_geometry_id = selected_geometry_indices_[first_index];
|
||||
const auto& first_geometry = geometry_model_.geometryObjects[first_geometry_id];
|
||||
for (std::size_t second_index = first_index + 1;
|
||||
second_index < selected_geometry_indices_.size();
|
||||
++second_index) {
|
||||
const auto second_geometry_id = selected_geometry_indices_[second_index];
|
||||
const auto& second_geometry = geometry_model_.geometryObjects[second_geometry_id];
|
||||
|
||||
if (first_geometry.parentJoint == second_geometry.parentJoint) {
|
||||
continue;
|
||||
}
|
||||
if (model_.parents[first_geometry.parentJoint] == second_geometry.parentJoint ||
|
||||
model_.parents[second_geometry.parentJoint] == first_geometry.parentJoint) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto link_pair = canonicalPair(
|
||||
geometry_link_names_[first_geometry_id],
|
||||
geometry_link_names_[second_geometry_id]);
|
||||
if (ignored_pairs.count(link_pair)) {
|
||||
continue;
|
||||
}
|
||||
geometry_model_.addCollisionPair(
|
||||
pinocchio::CollisionPair(first_geometry_id, second_geometry_id));
|
||||
}
|
||||
}
|
||||
|
||||
if (geometry_model_.collisionPairs.empty()) {
|
||||
setError(error, "No active collision pairs remain after filtering");
|
||||
reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
data_ = std::make_unique<pinocchio::Data>(model_);
|
||||
geometry_data_ = std::make_unique<pinocchio::GeometryData>(geometry_model_);
|
||||
for (auto& request : geometry_data_->distanceRequests) {
|
||||
request.enable_signed_distance = true;
|
||||
}
|
||||
neutral_q_ = pinocchio::neutral(model_);
|
||||
initialized_ = true;
|
||||
if (error) {
|
||||
error->clear();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool makeSnapshot(const std::vector<double>& joint_positions,
|
||||
CollisionGeometrySnapshot* snapshot,
|
||||
std::string* error)
|
||||
{
|
||||
if (!initialized_) {
|
||||
setError(error, "SelfCollisionChecker is not initialized");
|
||||
return false;
|
||||
}
|
||||
if (!snapshot) {
|
||||
setError(error, "Collision snapshot output is null");
|
||||
return false;
|
||||
}
|
||||
if (joint_positions.size() != joint_names_.size()) {
|
||||
std::ostringstream stream;
|
||||
stream << "Joint position size mismatch: expected " << joint_names_.size()
|
||||
<< ", got " << joint_positions.size();
|
||||
setError(error, stream.str());
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::VectorXd q = neutral_q_;
|
||||
for (std::size_t index = 0; index < joint_positions.size(); ++index) {
|
||||
if (!std::isfinite(joint_positions[index])) {
|
||||
setError(error, "Joint position contains a non-finite value: " + joint_names_[index]);
|
||||
return false;
|
||||
}
|
||||
q[joint_q_indices_[index]] = joint_positions[index];
|
||||
}
|
||||
|
||||
try {
|
||||
pinocchio::updateGeometryPlacements(
|
||||
model_, *data_, geometry_model_, *geometry_data_, q);
|
||||
} catch (const std::exception& exception) {
|
||||
setError(error, "Failed to update collision geometry: " + std::string(exception.what()));
|
||||
return false;
|
||||
}
|
||||
|
||||
snapshot->objects.clear();
|
||||
snapshot->objects.reserve(selected_geometry_indices_.size());
|
||||
for (const auto geometry_id : selected_geometry_indices_) {
|
||||
const auto& placement = geometry_data_->oMg[geometry_id];
|
||||
const auto& geometry = geometry_model_.geometryObjects[geometry_id];
|
||||
CollisionObjectPose pose;
|
||||
pose.geometry_index = geometry_id;
|
||||
pose.position = placement.translation();
|
||||
pose.orientation = Eigen::Quaterniond(placement.rotation()).normalized();
|
||||
pose.bounding_radius_m = std::max(0.0, geometry.geometry->aabb_radius);
|
||||
snapshot->objects.push_back(std::move(pose));
|
||||
}
|
||||
if (error) {
|
||||
error->clear();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot)
|
||||
{
|
||||
SelfCollisionResult result;
|
||||
if (!initialized_) {
|
||||
result.error = "SelfCollisionChecker is not initialized";
|
||||
return result;
|
||||
}
|
||||
if (snapshot.objects.size() != selected_geometry_indices_.size()) {
|
||||
result.error = "Collision snapshot size does not match initialized geometry";
|
||||
return result;
|
||||
}
|
||||
|
||||
for (std::size_t index = 0; index < snapshot.objects.size(); ++index) {
|
||||
const auto& pose = snapshot.objects[index];
|
||||
if (pose.geometry_index != selected_geometry_indices_[index] ||
|
||||
pose.geometry_index >= geometry_data_->oMg.size()) {
|
||||
result.error = "Collision snapshot geometry order is invalid";
|
||||
return result;
|
||||
}
|
||||
if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() ||
|
||||
pose.orientation.norm() <= std::numeric_limits<double>::epsilon()) {
|
||||
result.error = "Collision snapshot contains an invalid pose";
|
||||
return result;
|
||||
}
|
||||
geometry_data_->oMg[pose.geometry_index] = pinocchio::SE3(
|
||||
pose.orientation.normalized().toRotationMatrix(), pose.position);
|
||||
}
|
||||
|
||||
try {
|
||||
const std::size_t pair_index =
|
||||
pinocchio::computeDistances(geometry_model_, *geometry_data_);
|
||||
if (pair_index >= geometry_model_.collisionPairs.size()) {
|
||||
result.error = "Collision distance computation returned no active pair";
|
||||
return result;
|
||||
}
|
||||
const auto& pair = geometry_model_.collisionPairs[pair_index];
|
||||
result.minimum_distance_m = geometry_data_->distanceResults[pair_index].min_distance;
|
||||
result.first = geometry_link_names_[pair.first];
|
||||
result.second = geometry_link_names_[pair.second];
|
||||
result.in_collision = result.minimum_distance_m <= 0.0;
|
||||
result.valid = std::isfinite(result.minimum_distance_m);
|
||||
if (!result.valid) {
|
||||
result.error = "Collision distance is not finite";
|
||||
}
|
||||
} catch (const std::exception& exception) {
|
||||
result.error = "Collision distance computation failed: " + std::string(exception.what());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
SelfCollisionResult check(const std::vector<double>& joint_positions)
|
||||
{
|
||||
CollisionGeometrySnapshot snapshot;
|
||||
std::string error;
|
||||
if (!makeSnapshot(joint_positions, &snapshot, &error)) {
|
||||
SelfCollisionResult result;
|
||||
result.error = std::move(error);
|
||||
return result;
|
||||
}
|
||||
return check(snapshot);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
initialized_ = false;
|
||||
joint_names_.clear();
|
||||
joint_q_indices_.clear();
|
||||
selected_geometry_indices_.clear();
|
||||
geometry_link_names_.clear();
|
||||
geometry_data_.reset();
|
||||
data_.reset();
|
||||
model_ = pinocchio::Model{};
|
||||
geometry_model_ = pinocchio::GeometryModel{};
|
||||
neutral_q_.resize(0);
|
||||
}
|
||||
|
||||
bool initialized_{false};
|
||||
std::vector<std::string> joint_names_;
|
||||
std::vector<int> joint_q_indices_;
|
||||
std::vector<pinocchio::GeomIndex> selected_geometry_indices_;
|
||||
std::vector<std::string> geometry_link_names_;
|
||||
pinocchio::Model model_;
|
||||
pinocchio::GeometryModel geometry_model_;
|
||||
std::unique_ptr<pinocchio::Data> data_;
|
||||
std::unique_ptr<pinocchio::GeometryData> geometry_data_;
|
||||
Eigen::VectorXd neutral_q_;
|
||||
};
|
||||
|
||||
SelfCollisionChecker::SelfCollisionChecker()
|
||||
: impl_(std::make_unique<Impl>())
|
||||
{
|
||||
}
|
||||
|
||||
SelfCollisionChecker::~SelfCollisionChecker() = default;
|
||||
SelfCollisionChecker::SelfCollisionChecker(SelfCollisionChecker&&) noexcept = default;
|
||||
SelfCollisionChecker& SelfCollisionChecker::operator=(SelfCollisionChecker&&) noexcept = default;
|
||||
|
||||
bool SelfCollisionChecker::init(const std::string& urdf_path,
|
||||
const std::vector<std::string>& active_joint_names,
|
||||
const SelfCollisionOptions& options,
|
||||
std::string* error)
|
||||
{
|
||||
return impl_->init(urdf_path, active_joint_names, options, error);
|
||||
}
|
||||
|
||||
bool SelfCollisionChecker::makeSnapshot(const std::vector<double>& joint_positions,
|
||||
CollisionGeometrySnapshot* snapshot,
|
||||
std::string* error)
|
||||
{
|
||||
return impl_->makeSnapshot(joint_positions, snapshot, error);
|
||||
}
|
||||
|
||||
SelfCollisionResult SelfCollisionChecker::check(const CollisionGeometrySnapshot& snapshot)
|
||||
{
|
||||
return impl_->check(snapshot);
|
||||
}
|
||||
|
||||
SelfCollisionResult SelfCollisionChecker::check(const std::vector<double>& joint_positions)
|
||||
{
|
||||
return impl_->check(joint_positions);
|
||||
}
|
||||
|
||||
bool SelfCollisionChecker::initialized() const
|
||||
{
|
||||
return impl_->initialized_;
|
||||
}
|
||||
|
||||
std::size_t SelfCollisionChecker::dof() const
|
||||
{
|
||||
return impl_->joint_names_.size();
|
||||
}
|
||||
|
||||
std::size_t SelfCollisionChecker::activePairCount() const
|
||||
{
|
||||
return impl_->geometry_model_.collisionPairs.size();
|
||||
}
|
||||
|
||||
const std::vector<std::string>& SelfCollisionChecker::jointNames() const
|
||||
{
|
||||
return impl_->joint_names_;
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,236 +0,0 @@
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h"
|
||||
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
const std::vector<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";
|
||||
}
|
||||
|
||||
SelfCollisionOptions gen2CollisionOptions()
|
||||
{
|
||||
SelfCollisionOptions options;
|
||||
options.ignored_pairs.push_back({"arm_link_5_2", "arm_link_7_2"});
|
||||
options.ignored_pairs.push_back({"body_link", "arm_link_2_2"});
|
||||
return options;
|
||||
}
|
||||
|
||||
CollisionGeometrySnapshot singleObjectSnapshot(double x,
|
||||
double angle,
|
||||
double radius)
|
||||
{
|
||||
CollisionGeometrySnapshot snapshot;
|
||||
CollisionObjectPose pose;
|
||||
pose.geometry_index = 1;
|
||||
pose.position = Eigen::Vector3d(x, 0.0, 0.0);
|
||||
pose.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());
|
||||
pose.bounding_radius_m = radius;
|
||||
snapshot.objects.push_back(pose);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
TEST(SelfCollisionCheckerTest, LoadsRightArmFromDualArmUrdf)
|
||||
{
|
||||
SelfCollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
|
||||
EXPECT_EQ(checker.dof(), 7U);
|
||||
EXPECT_GT(checker.activePairCount(), 0U);
|
||||
|
||||
CollisionGeometrySnapshot snapshot;
|
||||
ASSERT_TRUE(checker.makeSnapshot(std::vector<double>(7, 0.0), &snapshot, &error)) << error;
|
||||
EXPECT_EQ(snapshot.objects.size(), 11U);
|
||||
|
||||
const SelfCollisionResult result = checker.check(snapshot);
|
||||
ASSERT_TRUE(result.valid) << result.error;
|
||||
EXPECT_TRUE(result.first.rfind("L_", 0) != 0);
|
||||
EXPECT_TRUE(result.second.rfind("L_", 0) != 0);
|
||||
}
|
||||
|
||||
TEST(SelfCollisionCheckerTest, RejectsWrongJointVectorSize)
|
||||
{
|
||||
SelfCollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
|
||||
|
||||
CollisionGeometrySnapshot snapshot;
|
||||
EXPECT_FALSE(checker.makeSnapshot(std::vector<double>(6, 0.0), &snapshot, &error));
|
||||
EXPECT_NE(error.find("size mismatch"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(SelfCollisionCheckerTest, RemovesConfiguredIgnoredPair)
|
||||
{
|
||||
SelfCollisionChecker baseline;
|
||||
SelfCollisionChecker filtered;
|
||||
std::string error;
|
||||
ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
|
||||
|
||||
SelfCollisionOptions options;
|
||||
options.ignored_pairs.push_back({"base_link", "R_ELBOW_R_S"});
|
||||
ASSERT_TRUE(filtered.init(collisionUrdfPath(), kRightArmJoints, options, &error)) << error;
|
||||
EXPECT_EQ(filtered.activePairCount() + 1, baseline.activePairCount());
|
||||
}
|
||||
|
||||
TEST(SelfCollisionCheckerTest, LoadsGen2RightArmCollisionModel)
|
||||
{
|
||||
SelfCollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(
|
||||
gen2CollisionUrdfPath(),
|
||||
kGen2RightArmJoints,
|
||||
gen2CollisionOptions(),
|
||||
&error)) << error;
|
||||
EXPECT_EQ(checker.dof(), 7U);
|
||||
EXPECT_EQ(checker.activePairCount(), 19U);
|
||||
|
||||
CollisionGeometrySnapshot snapshot;
|
||||
ASSERT_TRUE(checker.makeSnapshot(kGen2SetupPose, &snapshot, &error)) << error;
|
||||
EXPECT_EQ(snapshot.objects.size(), 8U);
|
||||
|
||||
const SelfCollisionResult setup_result = checker.check(snapshot);
|
||||
ASSERT_TRUE(setup_result.valid) << setup_result.error;
|
||||
EXPECT_FALSE(setup_result.in_collision);
|
||||
EXPECT_GT(setup_result.minimum_distance_m, 0.02);
|
||||
}
|
||||
|
||||
TEST(SelfCollisionCheckerTest, ClassifiesGen2SafetyDistances)
|
||||
{
|
||||
SelfCollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(
|
||||
gen2CollisionUrdfPath(),
|
||||
kGen2RightArmJoints,
|
||||
gen2CollisionOptions(),
|
||||
&error)) << error;
|
||||
|
||||
const SelfCollisionResult warning_result = checker.check(kGen2WarningPose);
|
||||
ASSERT_TRUE(warning_result.valid) << warning_result.error;
|
||||
EXPECT_FALSE(warning_result.in_collision);
|
||||
EXPECT_GT(warning_result.minimum_distance_m, 0.005);
|
||||
EXPECT_LE(warning_result.minimum_distance_m, 0.02);
|
||||
|
||||
const SelfCollisionResult stop_result = checker.check(kGen2StopPose);
|
||||
ASSERT_TRUE(stop_result.valid) << stop_result.error;
|
||||
EXPECT_FALSE(stop_result.in_collision);
|
||||
EXPECT_GT(stop_result.minimum_distance_m, 0.0);
|
||||
EXPECT_LE(stop_result.minimum_distance_m, 0.005);
|
||||
|
||||
const SelfCollisionResult collision_result = checker.check(kGen2CollisionPose);
|
||||
ASSERT_TRUE(collision_result.valid) << collision_result.error;
|
||||
EXPECT_TRUE(collision_result.in_collision);
|
||||
EXPECT_LE(collision_result.minimum_distance_m, 0.0);
|
||||
|
||||
const SelfCollisionResult torso_result =
|
||||
checker.check(kGen2TorsoCollisionPose);
|
||||
ASSERT_TRUE(torso_result.valid) << torso_result.error;
|
||||
EXPECT_TRUE(torso_result.in_collision);
|
||||
EXPECT_LE(torso_result.minimum_distance_m, 0.0);
|
||||
EXPECT_TRUE(torso_result.first == "body_link" ||
|
||||
torso_result.second == "body_link");
|
||||
}
|
||||
|
||||
TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement)
|
||||
{
|
||||
DistanceSamplingPolicy policy;
|
||||
DistanceSamplingOptions options;
|
||||
options.max_geometry_displacement_m = 0.002;
|
||||
options.max_check_period_s = 0.01;
|
||||
std::string error;
|
||||
ASSERT_TRUE(policy.configure(options, &error)) << error;
|
||||
|
||||
const auto start = DistanceSamplingPolicy::Clock::now();
|
||||
const auto initial = singleObjectSnapshot(0.0, 0.0, 0.2);
|
||||
EXPECT_TRUE(policy.shouldCheck(initial, start));
|
||||
policy.markChecked(initial, start);
|
||||
|
||||
EXPECT_FALSE(policy.shouldCheck(
|
||||
singleObjectSnapshot(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleObjectSnapshot(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleObjectSnapshot(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
initial, start + std::chrono::milliseconds(10)));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr
|
||||
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
|
||||
@ -1,4 +1,4 @@
|
||||
#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h"
|
||||
#include "algorithms/collision_detection/include/distance_sampling_policy.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@ -46,7 +46,7 @@ bool DistanceSamplingPolicy::configure(const DistanceSamplingOptions& options,
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& current,
|
||||
bool DistanceSamplingPolicy::shouldCheck(const std::vector<CollisionBody>& current,
|
||||
const Clock::time_point now) const
|
||||
{
|
||||
if (!configured_ || !has_baseline_) {
|
||||
@ -59,7 +59,7 @@ bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& curren
|
||||
return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m;
|
||||
}
|
||||
|
||||
void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& current,
|
||||
void DistanceSamplingPolicy::markChecked(const std::vector<CollisionBody>& current,
|
||||
const Clock::time_point now)
|
||||
{
|
||||
last_checked_ = current;
|
||||
@ -69,22 +69,22 @@ void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& curren
|
||||
|
||||
void DistanceSamplingPolicy::reset()
|
||||
{
|
||||
last_checked_.objects.clear();
|
||||
last_checked_.clear();
|
||||
last_check_time_ = Clock::time_point{};
|
||||
has_baseline_ = false;
|
||||
}
|
||||
|
||||
double DistanceSamplingPolicy::displacementSinceLastCheck(
|
||||
const CollisionGeometrySnapshot& current) const
|
||||
const std::vector<CollisionBody>& current) const
|
||||
{
|
||||
if (!has_baseline_ || current.objects.size() != last_checked_.objects.size()) {
|
||||
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.objects.size(); ++index) {
|
||||
const auto& previous = last_checked_.objects[index];
|
||||
const auto& now = current.objects[index];
|
||||
for (std::size_t index = 0; index < current.size(); ++index) {
|
||||
const auto& previous = last_checked_[index];
|
||||
const auto& now = current[index];
|
||||
if (previous.geometry_index != now.geometry_index) {
|
||||
return std::numeric_limits<double>::infinity();
|
||||
}
|
||||
@ -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)
|
||||
{
|
||||
DistanceSamplingPolicy policy;
|
||||
DistanceSamplingOptions options;
|
||||
options.max_geometry_displacement_m = 0.002;
|
||||
options.max_check_period_s = 0.01;
|
||||
std::string error;
|
||||
ASSERT_TRUE(policy.configure(options, &error)) << error;
|
||||
|
||||
const auto start = DistanceSamplingPolicy::Clock::now();
|
||||
const auto initial = singleBody(0.0, 0.0, 0.2);
|
||||
EXPECT_TRUE(policy.shouldCheck(initial, start));
|
||||
policy.markChecked(initial, start);
|
||||
|
||||
EXPECT_FALSE(policy.shouldCheck(
|
||||
singleBody(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleBody(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
singleBody(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2)));
|
||||
EXPECT_TRUE(policy.shouldCheck(
|
||||
initial, start + std::chrono::milliseconds(10)));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr
|
||||
@ -1,6 +1,3 @@
|
||||
|
||||
add_subdirectory(arm_control)
|
||||
|
||||
#find_package(VISP REQUIRED)
|
||||
|
||||
# 如果报 relocation ... can not be used when making a shared object; recompile with -fPIC ,说明SRC 中包含了test文件 ,test
|
||||
|
||||
@ -1,17 +0,0 @@
|
||||
add_library(arm_control SHARED
|
||||
src/cartesian_velocity_controller.cpp
|
||||
)
|
||||
|
||||
target_include_directories(arm_control PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_link_libraries(arm_control
|
||||
PUBLIC
|
||||
cmvr_es::algorithms::arm_motion
|
||||
)
|
||||
|
||||
add_library(cmvr_es::algorithms::arm_control ALIAS arm_control)
|
||||
install(TARGETS arm_control LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(cartesian_velocity_controller_test src/cartesian_velocity_controller_test.cpp)
|
||||
target_link_libraries(cartesian_velocity_controller_test PRIVATE
|
||||
cmvr_es::algorithms::arm_control gtest gtest_main pthread)
|
||||
@ -1,92 +0,0 @@
|
||||
#ifndef CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H
|
||||
#define CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class CartesianVelocityController {
|
||||
public:
|
||||
struct Config {
|
||||
double control_period_s{0.001};
|
||||
double stop_twist_norm{1e-9};
|
||||
double stop_command_velocity_norm{1e-3};
|
||||
double stop_measured_velocity_norm{1e-2};
|
||||
double stop_acceleration{0.5};
|
||||
double stop_timeout_s{2.0};
|
||||
};
|
||||
|
||||
using ReadStateCallback = std::function<bool(std::vector<double>& q, std::vector<double>& qd)>;
|
||||
using SendVelocityCallback = std::function<Result(const JointVelocityCommand& velocity, double acceleration)>;
|
||||
|
||||
CartesianVelocityController(Config config,
|
||||
std::shared_ptr<CartesianMotionPlanner> planner,
|
||||
std::size_t dof,
|
||||
ReadStateCallback read_state,
|
||||
SendVelocityCallback send_velocity);
|
||||
~CartesianVelocityController();
|
||||
|
||||
CartesianVelocityController(const CartesianVelocityController&) = delete;
|
||||
CartesianVelocityController& operator=(const CartesianVelocityController&) = delete;
|
||||
|
||||
Result speedL(const CartesianVelocity& velocity,
|
||||
double acceleration,
|
||||
double duration,
|
||||
FrameType frame);
|
||||
Result stop(std::optional<double> acceleration = std::nullopt);
|
||||
Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options,
|
||||
double duration, FrameType frame);
|
||||
SpeedLReference getReference() const;
|
||||
void shutdown();
|
||||
|
||||
bool busy() const { return busy_.load(); }
|
||||
double stopTimeoutS() const { return config_.stop_timeout_s; }
|
||||
CartesianVelocity getCommandTwistBase() const;
|
||||
|
||||
private:
|
||||
void ensureWorkerStarted_();
|
||||
void workerLoop_();
|
||||
void requestStop_(std::optional<double> acceleration = std::nullopt);
|
||||
void abortCommand_();
|
||||
void sendZero_();
|
||||
|
||||
static double velocityNorm_(const std::vector<double>& velocity);
|
||||
static double twistNorm_(const CartesianVelocity& velocity);
|
||||
|
||||
private:
|
||||
Config config_;
|
||||
std::shared_ptr<CartesianMotionPlanner> planner_;
|
||||
std::size_t dof_{0};
|
||||
ReadStateCallback read_state_;
|
||||
SendVelocityCallback send_velocity_;
|
||||
|
||||
std::unique_ptr<std::thread> worker_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::atomic<bool> stop_requested_{false};
|
||||
bool command_active_{false};
|
||||
CartesianVelocity target_twist_{};
|
||||
FrameType target_frame_{FrameType::Base};
|
||||
double target_acceleration_{0.25};
|
||||
SpeedLOptions target_options_{};
|
||||
SpeedLReference reference_{};
|
||||
CartesianVelocity command_twist_snapshot_{};
|
||||
std::uint64_t command_version_{0};
|
||||
std::atomic<bool> busy_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H
|
||||
@ -1,379 +0,0 @@
|
||||
#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
namespace {
|
||||
|
||||
CartesianVelocityController::Config normalizeConfig(CartesianVelocityController::Config config)
|
||||
{
|
||||
const CartesianVelocityController::Config defaults;
|
||||
if (config.control_period_s <= 0.0) {
|
||||
config.control_period_s = defaults.control_period_s;
|
||||
}
|
||||
if (config.stop_twist_norm <= 0.0) {
|
||||
config.stop_twist_norm = defaults.stop_twist_norm;
|
||||
}
|
||||
if (config.stop_command_velocity_norm <= 0.0) {
|
||||
config.stop_command_velocity_norm = defaults.stop_command_velocity_norm;
|
||||
}
|
||||
if (config.stop_measured_velocity_norm <= 0.0) {
|
||||
config.stop_measured_velocity_norm = defaults.stop_measured_velocity_norm;
|
||||
}
|
||||
if (config.stop_acceleration <= 0.0) {
|
||||
config.stop_acceleration = defaults.stop_acceleration;
|
||||
}
|
||||
if (!std::isfinite(config.stop_timeout_s) || config.stop_timeout_s <= 0.0) {
|
||||
config.stop_timeout_s = defaults.stop_timeout_s;
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CartesianVelocityController::CartesianVelocityController(
|
||||
Config config,
|
||||
std::shared_ptr<CartesianMotionPlanner> planner,
|
||||
const std::size_t dof,
|
||||
ReadStateCallback read_state,
|
||||
SendVelocityCallback send_velocity)
|
||||
: config_(normalizeConfig(config)),
|
||||
planner_(std::move(planner)),
|
||||
dof_(dof),
|
||||
read_state_(std::move(read_state)),
|
||||
send_velocity_(std::move(send_velocity))
|
||||
{
|
||||
}
|
||||
|
||||
CartesianVelocityController::~CartesianVelocityController()
|
||||
{
|
||||
shutdown();
|
||||
}
|
||||
|
||||
Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
|
||||
const double acceleration,
|
||||
const double duration,
|
||||
const FrameType frame)
|
||||
{
|
||||
SpeedLOptions options;
|
||||
options.acceleration = acceleration;
|
||||
return speedL(velocity, options, duration, frame);
|
||||
}
|
||||
|
||||
Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
|
||||
const SpeedLOptions& options,
|
||||
const double duration, const FrameType frame)
|
||||
{
|
||||
const double acceleration = options.acceleration;
|
||||
if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 ||
|
||||
!std::isfinite(acceleration) || acceleration <= 0.0 ||
|
||||
!std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) ||
|
||||
(options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) {
|
||||
return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input");
|
||||
}
|
||||
if (!worker_ || !worker_->joinable()) {
|
||||
if (busy_.exchange(true)) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy");
|
||||
}
|
||||
}
|
||||
|
||||
ensureWorkerStarted_();
|
||||
|
||||
std::uint64_t command_version = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
target_twist_ = velocity;
|
||||
target_acceleration_ = acceleration;
|
||||
target_frame_ = frame;
|
||||
target_options_ = options;
|
||||
reference_ = {};
|
||||
command_active_ = true;
|
||||
busy_.store(true);
|
||||
command_version = ++command_version_;
|
||||
}
|
||||
cv_.notify_all();
|
||||
|
||||
if (duration > 0.0) {
|
||||
std::this_thread::sleep_for(std::chrono::duration<double>(duration));
|
||||
bool should_stop = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (command_version_ == command_version) {
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
command_active_ = true;
|
||||
++command_version_;
|
||||
should_stop = true;
|
||||
}
|
||||
}
|
||||
if (should_stop) {
|
||||
cv_.notify_all();
|
||||
}
|
||||
}
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result CartesianVelocityController::stop(const std::optional<double> acceleration)
|
||||
{
|
||||
if (!worker_ || !worker_->joinable()) {
|
||||
return Result::success();
|
||||
}
|
||||
// A completed speedL command leaves the worker thread joinable but idle.
|
||||
// Do not turn that idle worker into a new command just because a caller
|
||||
// requests a stop during a task transition.
|
||||
if (!busy_.load()) {
|
||||
return Result::success();
|
||||
}
|
||||
requestStop_(acceleration);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
void CartesianVelocityController::shutdown()
|
||||
{
|
||||
if (!worker_ || !worker_->joinable()) {
|
||||
busy_.store(false);
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stop_requested_.store(true);
|
||||
command_active_ = false;
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
}
|
||||
cv_.notify_all();
|
||||
worker_->join();
|
||||
worker_.reset();
|
||||
stop_requested_.store(false);
|
||||
busy_.store(false);
|
||||
}
|
||||
|
||||
CartesianVelocity CartesianVelocityController::getCommandTwistBase() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return command_twist_snapshot_;
|
||||
}
|
||||
|
||||
SpeedLReference CartesianVelocityController::getReference() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return reference_;
|
||||
}
|
||||
|
||||
void CartesianVelocityController::ensureWorkerStarted_()
|
||||
{
|
||||
if (worker_ && worker_->joinable()) {
|
||||
return;
|
||||
}
|
||||
stop_requested_.store(false);
|
||||
worker_ = std::make_unique<std::thread>(&CartesianVelocityController::workerLoop_, this);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::workerLoop_()
|
||||
{
|
||||
const double dt = config_.control_period_s;
|
||||
auto next_tick = std::chrono::steady_clock::now();
|
||||
|
||||
while (true) {
|
||||
CartesianVelocity target_twist;
|
||||
double acceleration = 0.25;
|
||||
FrameType target_frame = FrameType::Base;
|
||||
SpeedLOptions options;
|
||||
std::uint64_t applied_version = 0;
|
||||
bool capture_reference = false;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
cv_.wait(lock, [&]() {
|
||||
return stop_requested_.load() || command_active_;
|
||||
});
|
||||
if (stop_requested_.load()) {
|
||||
break;
|
||||
}
|
||||
target_twist = target_twist_;
|
||||
acceleration = target_acceleration_;
|
||||
target_frame = target_frame_;
|
||||
}
|
||||
|
||||
next_tick = std::chrono::steady_clock::now();
|
||||
while (true) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (stop_requested_.load()) {
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
return;
|
||||
}
|
||||
if (!command_active_) {
|
||||
break;
|
||||
}
|
||||
target_twist = target_twist_;
|
||||
acceleration = target_acceleration_;
|
||||
target_frame = target_frame_;
|
||||
options = target_options_;
|
||||
options.acceleration = acceleration;
|
||||
applied_version = command_version_;
|
||||
capture_reference = options.capture_reference && !reference_.valid;
|
||||
}
|
||||
|
||||
if (!planner_->updateSpeedLLimits(options)) {
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
|
||||
abortCommand_();
|
||||
break;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] updateSpeedLAcceleration failed, acceleration="
|
||||
<< acceleration;
|
||||
requestStop_();
|
||||
continue;
|
||||
}
|
||||
|
||||
std::vector<double> q_now;
|
||||
std::vector<double> qd_now;
|
||||
if (!read_state_(q_now, qd_now)) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] read_state failed";
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
|
||||
abortCommand_();
|
||||
break;
|
||||
}
|
||||
requestStop_();
|
||||
continue;
|
||||
}
|
||||
|
||||
std::vector<double> qd_cmd;
|
||||
SpeedLReference reference;
|
||||
if (capture_reference &&
|
||||
!planner_->captureSpeedLReference(q_now, target_twist, target_frame, reference)) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] cannot capture motion reference";
|
||||
abortCommand_();
|
||||
break;
|
||||
}
|
||||
if (!planner_->speedLStep(target_twist, dt, q_now, qd_now, qd_cmd, target_frame)) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] speedLStep failed, target_twist=["
|
||||
<< target_twist.vx << ", " << target_twist.vy << ", "
|
||||
<< target_twist.vz << ", " << target_twist.wx << ", "
|
||||
<< target_twist.wy << ", " << target_twist.wz
|
||||
<< "], frame=" << (target_frame == FrameType::Tool ? "Tool" : "Base");
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
|
||||
abortCommand_();
|
||||
break;
|
||||
}
|
||||
requestStop_();
|
||||
continue;
|
||||
}
|
||||
|
||||
JointVelocityCommand velocity_command;
|
||||
velocity_command.velocity = qd_cmd;
|
||||
const auto send_result = send_velocity_(velocity_command, acceleration);
|
||||
if (!send_result.ok()) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: "
|
||||
<< send_result.message;
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
|
||||
abortCommand_();
|
||||
break;
|
||||
}
|
||||
requestStop_();
|
||||
continue;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
command_twist_snapshot_ = planner_->getSpeedLCommandTwistBase();
|
||||
if (capture_reference && command_version_ == applied_version) {
|
||||
reference.command_version = applied_version;
|
||||
reference_ = reference;
|
||||
// Lock a captured Tool-frame translation in Base for the
|
||||
// entire command, matching its distance reference axis.
|
||||
target_twist_ = reference.target_base;
|
||||
target_frame_ = FrameType::Base;
|
||||
}
|
||||
}
|
||||
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm &&
|
||||
velocityNorm_(qd_cmd) < config_.stop_command_velocity_norm &&
|
||||
velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// A newer target may have arrived during planning/I/O.
|
||||
if (command_version_ != applied_version) continue;
|
||||
command_active_ = false;
|
||||
// Serialize the final zero and busy transition with new
|
||||
// submissions, not only the version comparison.
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
next_tick += std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(dt));
|
||||
std::this_thread::sleep_until(next_tick);
|
||||
}
|
||||
}
|
||||
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::requestStop_(const std::optional<double> acceleration)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
target_acceleration_ = acceleration.has_value() ? *acceleration
|
||||
: config_.stop_acceleration;
|
||||
target_options_.acceleration = target_acceleration_;
|
||||
target_options_.capture_reference = false;
|
||||
command_active_ = true;
|
||||
++command_version_;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
void CartesianVelocityController::abortCommand_()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
command_active_ = false;
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
}
|
||||
}
|
||||
|
||||
void CartesianVelocityController::sendZero_()
|
||||
{
|
||||
if (!send_velocity_) {
|
||||
return;
|
||||
}
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(dof_, 0.0);
|
||||
(void)send_velocity_(zero, 0.0);
|
||||
}
|
||||
|
||||
double CartesianVelocityController::velocityNorm_(const std::vector<double>& velocity)
|
||||
{
|
||||
double value = 0.0;
|
||||
for (const double item : velocity) {
|
||||
value += item * item;
|
||||
}
|
||||
return std::sqrt(value);
|
||||
}
|
||||
|
||||
double CartesianVelocityController::twistNorm_(const CartesianVelocity& velocity)
|
||||
{
|
||||
return std::sqrt(velocity.vx * velocity.vx +
|
||||
velocity.vy * velocity.vy +
|
||||
velocity.vz * velocity.vz +
|
||||
velocity.wx * velocity.wx +
|
||||
velocity.wy * velocity.wy +
|
||||
velocity.wz * velocity.wz);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,131 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h"
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <limits>
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
using namespace std::chrono_literals;
|
||||
class Planner final : public CartesianMotionPlanner {
|
||||
public:
|
||||
bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; }
|
||||
bool configureMoveL(const config::MoveLPlannerConfig&) override { return true; }
|
||||
bool planMoveL(const CartesianPose&, const std::vector<double>&, const std::vector<double>&,
|
||||
double, double, double, FrameType, CartesianJointTrajectory&) override { return false; }
|
||||
bool updateSpeedLAcceleration(double) override { return true; }
|
||||
bool updateSpeedLLimits(const SpeedLOptions& options) override {
|
||||
applied_reversal.store(options.continuous_linear_reversal.value_or(false));
|
||||
applied_jerk.store(options.linear_jerk.value_or(10.0)); return true;
|
||||
}
|
||||
bool captureSpeedLReference(const std::vector<double>&, const CartesianVelocity& target,
|
||||
FrameType, SpeedLReference& ref) override {
|
||||
ref.valid = true;
|
||||
ref.tcp_pose_base.y = .5;
|
||||
ref.target_base.vx = target.vy;
|
||||
return true;
|
||||
}
|
||||
bool speedLStep(const CartesianVelocity& v, double, const std::vector<double>&,
|
||||
const std::vector<double>&, std::vector<double>& out, FrameType) override {
|
||||
current = v; out = {v.vy}; return true;
|
||||
}
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override { return current; }
|
||||
CartesianVelocity current;
|
||||
std::atomic<double> applied_jerk{0.0};
|
||||
std::atomic<bool> applied_reversal{false};
|
||||
};
|
||||
TEST(CartesianVelocityController, CompletedStopCannotClearNewReversal) {
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
bool forward_sent = false, block_zero = false, zero_entered = false;
|
||||
bool release_zero = false, reverse_sent = false;
|
||||
auto planner = std::make_shared<Planner>();
|
||||
CartesianVelocityController controller({}, planner, 1,
|
||||
[](auto& q, auto& qd) { q = {0}; qd = {0}; return true; },
|
||||
[&](const JointVelocityCommand& command, double) {
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
forward_sent |= command.velocity[0] > 0;
|
||||
reverse_sent |= command.velocity[0] < 0;
|
||||
if (command.velocity[0] == 0 && block_zero && !zero_entered) {
|
||||
zero_entered = true; cv.notify_all();
|
||||
cv.wait_for(lock, 2s, [&] { return release_zero; });
|
||||
}
|
||||
cv.notify_all(); return Result::success();
|
||||
});
|
||||
CartesianVelocity v; v.vy = .08;
|
||||
ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok());
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; }));
|
||||
block_zero = true;
|
||||
}
|
||||
ASSERT_TRUE(controller.stop(3).ok());
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; }));
|
||||
}
|
||||
v.vy = -.08;
|
||||
ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok());
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
release_zero = true; cv.notify_all();
|
||||
EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; }));
|
||||
}
|
||||
EXPECT_TRUE(controller.busy());
|
||||
controller.shutdown();
|
||||
}
|
||||
TEST(CartesianVelocityController, PublishesReferenceAfterSendAndKeepsCommandLimits) {
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
bool entered = false, release = false;
|
||||
auto planner = std::make_shared<Planner>();
|
||||
CartesianVelocityController controller({}, planner, 1,
|
||||
[](auto& q, auto& qd) { q = {0}; qd = {0}; return true; },
|
||||
[&](const JointVelocityCommand&, double) {
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
if (!entered) {
|
||||
entered = true; cv.notify_all();
|
||||
cv.wait_for(lock, 2s, [&] { return release; });
|
||||
}
|
||||
return Result::success();
|
||||
});
|
||||
CartesianVelocity v; v.vy = -.08;
|
||||
SpeedLOptions options;
|
||||
options.acceleration = 3;
|
||||
options.linear_jerk = 60;
|
||||
options.continuous_linear_reversal = true;
|
||||
options.capture_reference = true;
|
||||
ASSERT_TRUE(controller.speedL(v, options, 0, FrameType::Tool).ok());
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; }));
|
||||
EXPECT_FALSE(controller.getReference().valid);
|
||||
release = true; cv.notify_all();
|
||||
}
|
||||
const auto deadline = std::chrono::steady_clock::now() + 1s;
|
||||
while (!controller.getReference().valid && std::chrono::steady_clock::now() < deadline)
|
||||
std::this_thread::sleep_for(1ms);
|
||||
const auto ref = controller.getReference();
|
||||
EXPECT_TRUE(ref.valid);
|
||||
EXPECT_GT(ref.command_version, 0U);
|
||||
EXPECT_DOUBLE_EQ(ref.tcp_pose_base.y, .5);
|
||||
EXPECT_DOUBLE_EQ(ref.target_base.vx, -.08);
|
||||
EXPECT_DOUBLE_EQ(planner->applied_jerk.load(), 60);
|
||||
EXPECT_TRUE(planner->applied_reversal.load());
|
||||
controller.shutdown();
|
||||
}
|
||||
TEST(CartesianVelocityController, RejectsInvalidMotionLimitsBeforeStarting) {
|
||||
auto planner = std::make_shared<Planner>();
|
||||
CartesianVelocityController controller({}, planner, 1,
|
||||
[](auto&, auto&) { return false; },
|
||||
[](const auto&, double) { return Result::success(); });
|
||||
SpeedLOptions options;
|
||||
options.linear_jerk = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok());
|
||||
options.linear_jerk = -1;
|
||||
EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok());
|
||||
EXPECT_FALSE(controller.busy());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -9,7 +9,8 @@
|
||||
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief 基于相对 3D 位姿的 PBVS 控制器。
|
||||
@ -44,7 +45,6 @@ namespace cmvr {
|
||||
* 姿态误差:
|
||||
*
|
||||
* R_err = R_des * R_cur^T
|
||||
*
|
||||
* e_R = Log(R_err)^vee
|
||||
*
|
||||
* 控制律:
|
||||
@ -60,9 +60,11 @@ namespace cmvr {
|
||||
* - IK
|
||||
* - speedL 下发
|
||||
*/
|
||||
class PbvsController {
|
||||
class PbvsController
|
||||
{
|
||||
public:
|
||||
enum class ComputeStatus {
|
||||
enum class ComputeStatus
|
||||
{
|
||||
OK = 0,
|
||||
TARGET_NOT_SET,
|
||||
INVALID_INPUT,
|
||||
@ -71,36 +73,25 @@ public:
|
||||
INVALID_CURRENT_POSE
|
||||
};
|
||||
|
||||
struct Output {
|
||||
struct Output
|
||||
{
|
||||
// 当前位置误差,单位 m
|
||||
Eigen::Vector3d position_error_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d position_error_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// 当前姿态误差 rotation-vector,单位 rad
|
||||
Eigen::Vector3d rotation_error_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d rotation_error_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// PBVS 计算得到的原始线速度,单位 m/s
|
||||
Eigen::Vector3d raw_linear_velocity_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d raw_linear_velocity_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// PBVS 计算得到的原始角速度,单位 rad/s
|
||||
Eigen::Vector3d raw_angular_velocity_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d raw_angular_velocity_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// 经过限幅 / 加速度 / 滤波后的线速度
|
||||
Eigen::Vector3d linear_velocity_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d linear_velocity_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// 经过限幅 / 加速度 / 滤波后的角速度
|
||||
Eigen::Vector3d angular_velocity_G{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d angular_velocity_G{Eigen::Vector3d::Zero()};
|
||||
|
||||
// 可直接取出的 CartesianVelocity。
|
||||
//
|
||||
@ -111,7 +102,6 @@ public:
|
||||
bool position_reached{false};
|
||||
bool orientation_reached{false};
|
||||
bool reached{false};
|
||||
|
||||
bool valid{false};
|
||||
};
|
||||
|
||||
@ -123,8 +113,7 @@ public:
|
||||
*
|
||||
* @param T_G_P_des TCP(P) 相对于 ScreenTag(G) 的目标位姿。
|
||||
*/
|
||||
bool setTargetPose(
|
||||
const Eigen::Matrix4d& T_G_P_des);
|
||||
bool setTargetPose(const Eigen::Matrix4d& T_G_P_des);
|
||||
|
||||
/**
|
||||
* @brief 使用目标位置 + 目标姿态设置期望位姿。
|
||||
@ -136,16 +125,12 @@ public:
|
||||
/**
|
||||
* @brief 当前是否已经设置有效目标。
|
||||
*/
|
||||
bool hasTarget() const {
|
||||
return target_valid_;
|
||||
}
|
||||
bool hasTarget() const { return target_valid_; }
|
||||
|
||||
/**
|
||||
* @brief 获取目标位姿。
|
||||
*/
|
||||
const Eigen::Matrix4d& targetPose() const {
|
||||
return T_G_P_des_;
|
||||
}
|
||||
const Eigen::Matrix4d& targetPose() const { return T_G_P_des_; }
|
||||
|
||||
/**
|
||||
* @brief 根据当前 TCP 位姿计算 PBVS 速度命令。
|
||||
@ -176,16 +161,14 @@ public:
|
||||
*
|
||||
* x/y/z 分别控制。
|
||||
*/
|
||||
void setPositionGain(
|
||||
const Eigen::Vector3d& kp);
|
||||
void setPositionGain(const Eigen::Vector3d& kp);
|
||||
|
||||
/**
|
||||
* @brief 设置姿态比例增益。
|
||||
*
|
||||
* rx/ry/rz 分别控制。
|
||||
*/
|
||||
void setRotationGain(
|
||||
const Eigen::Vector3d& kr);
|
||||
void setRotationGain(const Eigen::Vector3d& kr);
|
||||
|
||||
/**
|
||||
* @brief 设置六维速度上限。
|
||||
@ -195,8 +178,7 @@ public:
|
||||
* 前三维 m/s;
|
||||
* 后三维 rad/s。
|
||||
*/
|
||||
void setVelocityLimit6(
|
||||
const std::array<double, 6>& vmax6);
|
||||
void setVelocityLimit6(const std::array<double, 6>& vmax6);
|
||||
|
||||
/**
|
||||
* @brief 设置六维加速度限制。
|
||||
@ -206,8 +188,7 @@ public:
|
||||
*
|
||||
* <= 0 表示对应维度不限制。
|
||||
*/
|
||||
void setAccelerationLimit6(
|
||||
const std::array<double, 6>& amax6);
|
||||
void setAccelerationLimit6(const std::array<double, 6>& amax6);
|
||||
|
||||
/**
|
||||
* @brief 设置六维误差阈值。
|
||||
@ -217,21 +198,16 @@ public:
|
||||
* 前三维 m;
|
||||
* 后三维 rad。
|
||||
*/
|
||||
void setTolerance6(
|
||||
const std::array<double, 6>& tolerance6);
|
||||
void setTolerance6(const std::array<double, 6>& tolerance6);
|
||||
|
||||
/**
|
||||
* @brief 设置一阶低通 alpha。
|
||||
*
|
||||
* alpha = 1:
|
||||
* 不滤波。
|
||||
* alpha = 1:不滤波。
|
||||
*
|
||||
* 0 < alpha < 1:
|
||||
*
|
||||
* cmd =
|
||||
* alpha * current
|
||||
* +
|
||||
* (1-alpha) * previous
|
||||
* cmd = alpha * current + (1 - alpha) * previous
|
||||
*/
|
||||
void setTwistFilterAlpha(double alpha);
|
||||
|
||||
@ -244,8 +220,7 @@ public:
|
||||
*
|
||||
* enabled[5] = false;
|
||||
*/
|
||||
void setAxisEnabled(
|
||||
const std::array<bool, 6>& enabled);
|
||||
void setAxisEnabled(const std::array<bool, 6>& enabled);
|
||||
|
||||
/**
|
||||
* @brief 清空速度历史,但保留目标。
|
||||
@ -257,70 +232,42 @@ public:
|
||||
*/
|
||||
void reset();
|
||||
|
||||
ComputeStatus lastComputeStatus() const {
|
||||
return last_compute_status_;
|
||||
}
|
||||
ComputeStatus lastComputeStatus() const { return last_compute_status_; }
|
||||
|
||||
static const char* statusToString(
|
||||
ComputeStatus status);
|
||||
static const char* statusToString(ComputeStatus status);
|
||||
|
||||
const Eigen::Vector3d& lastPositionError() const {
|
||||
return last_position_error_G_;
|
||||
}
|
||||
const Eigen::Vector3d& lastPositionError() const { return last_position_error_G_; }
|
||||
const Eigen::Vector3d& lastRotationError() const { return last_rotation_error_G_; }
|
||||
|
||||
const Eigen::Vector3d& lastRotationError() const {
|
||||
return last_rotation_error_G_;
|
||||
}
|
||||
const Eigen::Vector3d& positionGain() const { return kp_position_; }
|
||||
const Eigen::Vector3d& rotationGain() const { return kp_rotation_; }
|
||||
|
||||
const Eigen::Vector3d& positionGain() const {
|
||||
return kp_position_;
|
||||
}
|
||||
const std::array<double, 6>& velocityLimit6() const { return vmax6_; }
|
||||
const std::array<double, 6>& accelerationLimit6() const { return amax6_; }
|
||||
const std::array<double, 6>& tolerance6() const { return tolerance6_; }
|
||||
|
||||
const Eigen::Vector3d& rotationGain() const {
|
||||
return kp_rotation_;
|
||||
}
|
||||
double twistFilterAlpha() const { return twist_lpf_alpha_; }
|
||||
|
||||
const std::array<double, 6>& velocityLimit6() const {
|
||||
return vmax6_;
|
||||
}
|
||||
|
||||
const std::array<double, 6>& accelerationLimit6() const {
|
||||
return amax6_;
|
||||
}
|
||||
|
||||
const std::array<double, 6>& tolerance6() const {
|
||||
return tolerance6_;
|
||||
}
|
||||
|
||||
double twistFilterAlpha() const {
|
||||
return twist_lpf_alpha_;
|
||||
}
|
||||
|
||||
const Eigen::Matrix<double, 6, 1>&
|
||||
lastTwistCommandG() const {
|
||||
const Eigen::Matrix<double, 6, 1>& lastTwistCommandG() const
|
||||
{
|
||||
return last_twist_cmd_G_;
|
||||
}
|
||||
|
||||
bool lastReached() const {
|
||||
return last_reached_;
|
||||
}
|
||||
bool lastReached() const { return last_reached_; }
|
||||
|
||||
private:
|
||||
static bool isFiniteTransform(
|
||||
const Eigen::Matrix4d& T);
|
||||
static bool isFiniteTransform(const Eigen::Matrix4d& T);
|
||||
|
||||
static bool hasValidBottomRow(
|
||||
const Eigen::Matrix4d& T,
|
||||
double tolerance = 1e-6);
|
||||
|
||||
static bool isValidTransform(
|
||||
const Eigen::Matrix4d& T);
|
||||
static bool isValidTransform(const Eigen::Matrix4d& T);
|
||||
|
||||
/**
|
||||
* @brief 将可能有微小数值误差的旋转矩阵投影到 SO(3)。
|
||||
*/
|
||||
static Eigen::Matrix3d projectToSO3(
|
||||
const Eigen::Matrix3d& R);
|
||||
static Eigen::Matrix3d projectToSO3(const Eigen::Matrix3d& R);
|
||||
|
||||
/**
|
||||
* @brief 计算空间旋转误差,在 G frame 表达。
|
||||
@ -333,43 +280,27 @@ private:
|
||||
const Eigen::Matrix3d& R_des,
|
||||
const Eigen::Matrix3d& R_cur);
|
||||
|
||||
static double clampValue(
|
||||
double value,
|
||||
double lower,
|
||||
double upper);
|
||||
static double clampValue(double value, double lower, double upper);
|
||||
|
||||
static device::CartesianVelocity
|
||||
toCartesianVelocity(
|
||||
static device::CartesianVelocity toCartesianVelocity(
|
||||
const Eigen::Matrix<double, 6, 1>& twist);
|
||||
|
||||
private:
|
||||
// ---------------- target ----------------
|
||||
|
||||
Eigen::Matrix4d T_G_P_des_{
|
||||
Eigen::Matrix4d::Identity()
|
||||
};
|
||||
|
||||
Eigen::Matrix4d T_G_P_des_{Eigen::Matrix4d::Identity()};
|
||||
bool target_valid_{false};
|
||||
|
||||
// ---------------- gains ----------------
|
||||
|
||||
Eigen::Vector3d kp_position_{
|
||||
2.0,
|
||||
2.0,
|
||||
1.5
|
||||
};
|
||||
|
||||
Eigen::Vector3d kp_rotation_{
|
||||
1.5,
|
||||
1.5,
|
||||
1.5
|
||||
};
|
||||
Eigen::Vector3d kp_position_{2.0, 2.0, 1.5};
|
||||
Eigen::Vector3d kp_rotation_{1.5, 1.5, 1.5};
|
||||
|
||||
// ---------------- velocity limits ----------------
|
||||
|
||||
//
|
||||
// [vx vy vz wx wy wz]
|
||||
//
|
||||
|
||||
std::array<double, 6> vmax6_{{
|
||||
0.10,
|
||||
0.10,
|
||||
@ -393,13 +324,12 @@ private:
|
||||
// ---------------- tolerance ----------------
|
||||
|
||||
std::array<double, 6> tolerance6_{{
|
||||
0.0015, // x 1.5 mm
|
||||
0.0015, // y 1.5 mm
|
||||
0.0020, // z 2.0 mm
|
||||
|
||||
0.05, // rx ~2.9 deg
|
||||
0.05, // ry
|
||||
0.05 // rz
|
||||
0.0015, // x 1.5 mm
|
||||
0.0015, // y 1.5 mm
|
||||
0.0020, // z 2.0 mm
|
||||
0.05, // rx ~2.9 deg
|
||||
0.05, // ry
|
||||
0.05 // rz
|
||||
}};
|
||||
|
||||
// ---------------- axis enable ----------------
|
||||
@ -419,33 +349,24 @@ private:
|
||||
|
||||
// ---------------- command history ----------------
|
||||
|
||||
Eigen::Matrix<double, 6, 1>
|
||||
previous_twist_cmd_G_{
|
||||
Eigen::Matrix<double, 6, 1>::Zero()
|
||||
};
|
||||
Eigen::Matrix<double, 6, 1> previous_twist_cmd_G_{
|
||||
Eigen::Matrix<double, 6, 1>::Zero()
|
||||
};
|
||||
|
||||
bool has_previous_twist_{false};
|
||||
|
||||
// ---------------- last output ----------------
|
||||
|
||||
Eigen::Vector3d last_position_error_G_{
|
||||
Eigen::Vector3d::Zero()
|
||||
};
|
||||
Eigen::Vector3d last_position_error_G_{Eigen::Vector3d::Zero()};
|
||||
Eigen::Vector3d last_rotation_error_G_{Eigen::Vector3d::Zero()};
|
||||
|
||||
Eigen::Vector3d last_rotation_error_G_{
|
||||
Eigen::Vector3d::Zero()
|
||||
Eigen::Matrix<double, 6, 1> last_twist_cmd_G_{
|
||||
Eigen::Matrix<double, 6, 1>::Zero()
|
||||
};
|
||||
|
||||
Eigen::Matrix<double, 6, 1>
|
||||
last_twist_cmd_G_{
|
||||
Eigen::Matrix<double, 6, 1>::Zero()
|
||||
};
|
||||
|
||||
bool last_reached_{false};
|
||||
|
||||
ComputeStatus last_compute_status_{
|
||||
ComputeStatus::TARGET_NOT_SET
|
||||
};
|
||||
ComputeStatus last_compute_status_{ComputeStatus::TARGET_NOT_SET};
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -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};
|
||||
|
||||
|
||||
@ -6,15 +6,14 @@
|
||||
|
||||
#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 +63,24 @@ 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_; }
|
||||
|
||||
private:
|
||||
pinocchio::Model model_;
|
||||
bool loaded_{false};
|
||||
static bool extractChain(const RobotModel& robot_model,
|
||||
const std::string& base_frame_name,
|
||||
const std::string& tip_frame_name,
|
||||
ChainInfo& out,
|
||||
std::string* error = nullptr);
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
|
||||
@ -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
|
||||
|
||||
@ -1,2 +0,0 @@
|
||||
add_subdirectory(base_motion)
|
||||
add_subdirectory(arm_motion)
|
||||
@ -1,35 +0,0 @@
|
||||
add_library(arm_motion SHARED
|
||||
cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp
|
||||
joint_motion/toppra/src/toppra_joint_motion_planner.cpp
|
||||
)
|
||||
|
||||
target_include_directories(arm_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_link_libraries(arm_motion
|
||||
PUBLIC
|
||||
cmvr_es::ik_solver
|
||||
cmvr_es::base_motion
|
||||
)
|
||||
|
||||
add_library(cmvr_es::arm_motion ALIAS arm_motion)
|
||||
add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion)
|
||||
install(TARGETS arm_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(toppra_joint_motion_planner_test
|
||||
joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(toppra_joint_motion_planner_test
|
||||
PRIVATE
|
||||
cmvr_es::algorithms::arm_motion
|
||||
gtest
|
||||
gtest_main
|
||||
)
|
||||
|
||||
add_executable(pinocchio_speedl_limits_test
|
||||
cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp
|
||||
)
|
||||
target_compile_definitions(pinocchio_speedl_limits_test PRIVATE
|
||||
CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(pinocchio_speedl_limits_test PRIVATE
|
||||
cmvr_es::algorithms::arm_motion gtest gtest_main)
|
||||
@ -1,58 +0,0 @@
|
||||
#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_H
|
||||
#define CMVR_ES_CARTESIAN_MOTION_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;
|
||||
};
|
||||
|
||||
class CartesianMotionPlanner {
|
||||
public:
|
||||
virtual ~CartesianMotionPlanner() = default;
|
||||
|
||||
virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config,
|
||||
std::size_t dof) = 0;
|
||||
virtual bool configureMoveL(const config::MoveLPlannerConfig& config) = 0;
|
||||
|
||||
virtual bool planMoveL(const CartesianPose& target,
|
||||
const std::vector<double>& q_start,
|
||||
const std::vector<double>& qd_max,
|
||||
double velocity,
|
||||
double acceleration,
|
||||
double jerk,
|
||||
FrameType frame,
|
||||
CartesianJointTrajectory& trajectory) = 0;
|
||||
|
||||
virtual bool speedLStep(const CartesianVelocity& target_velocity,
|
||||
double dt,
|
||||
const std::vector<double>& q_measured,
|
||||
const std::vector<double>& qd_measured,
|
||||
std::vector<double>& qd_command,
|
||||
FrameType frame) = 0;
|
||||
|
||||
virtual bool updateSpeedLAcceleration(double acceleration) = 0;
|
||||
virtual bool updateSpeedLLimits(const SpeedLOptions& options) {
|
||||
return !options.linear_jerk && !options.continuous_linear_reversal.value_or(false) &&
|
||||
updateSpeedLAcceleration(options.acceleration);
|
||||
}
|
||||
virtual bool captureSpeedLReference(const std::vector<double>&,
|
||||
const CartesianVelocity&, FrameType, SpeedLReference&) { return false; }
|
||||
virtual CartesianVelocity getSpeedLCommandTwistBase() const = 0;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_H
|
||||
@ -1,63 +0,0 @@
|
||||
#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/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h"
|
||||
#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h"
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class CartesianMotionPlannerFactory {
|
||||
public:
|
||||
static std::shared_ptr<CartesianMotionPlanner> create(
|
||||
const config::MoveLConfig& move_l,
|
||||
const config::SpeedLConfig& speed_l,
|
||||
const std::shared_ptr<cmvr::PinocchioIKBase>& solver)
|
||||
{
|
||||
if (!solver) {
|
||||
return nullptr;
|
||||
}
|
||||
switch (move_l.algorithm_case()) {
|
||||
case config::MoveLConfig::kPinocchioCartesianMotionPlanner:
|
||||
if (speed_l.algorithm_case() !=
|
||||
config::SpeedLConfig::kPinocchioCartesianMotionPlanner) {
|
||||
return nullptr;
|
||||
}
|
||||
return std::make_shared<PinocchioCartesianMotionPlanner>(solver);
|
||||
case config::MoveLConfig::ALGORITHM_NOT_SET:
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
static const config::SpeedLPlannerConfig* speedLConfig(
|
||||
const config::SpeedLConfig& cfg)
|
||||
{
|
||||
switch (cfg.algorithm_case()) {
|
||||
case config::SpeedLConfig::kPinocchioCartesianMotionPlanner:
|
||||
return &cfg.pinocchio_cartesian_motion_planner();
|
||||
case config::SpeedLConfig::ALGORITHM_NOT_SET:
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
static const config::MoveLPlannerConfig* moveLConfig(
|
||||
const config::MoveLConfig& cfg)
|
||||
{
|
||||
switch (cfg.algorithm_case()) {
|
||||
case config::MoveLConfig::kPinocchioCartesianMotionPlanner:
|
||||
return &cfg.pinocchio_cartesian_motion_planner();
|
||||
case config::MoveLConfig::ALGORITHM_NOT_SET:
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H
|
||||
@ -1,117 +0,0 @@
|
||||
#ifndef CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H
|
||||
#define CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H
|
||||
|
||||
#include <Eigen/Core>
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h"
|
||||
#include "../../cartesian_motion_planner.h"
|
||||
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class PinocchioCartesianMotionPlanner final : public CartesianMotionPlanner {
|
||||
public:
|
||||
explicit PinocchioCartesianMotionPlanner(std::shared_ptr<cmvr::PinocchioIKBase> solver);
|
||||
|
||||
bool configureSpeedL(const config::SpeedLPlannerConfig& config,
|
||||
std::size_t dof) override;
|
||||
bool configureMoveL(const config::MoveLPlannerConfig& config) override;
|
||||
|
||||
bool planMoveL(const CartesianPose& target,
|
||||
const std::vector<double>& q_start,
|
||||
const std::vector<double>& qd_max,
|
||||
double velocity,
|
||||
double acceleration,
|
||||
double jerk,
|
||||
FrameType frame,
|
||||
CartesianJointTrajectory& trajectory) override;
|
||||
|
||||
bool speedLStep(const CartesianVelocity& target_velocity,
|
||||
double dt,
|
||||
const std::vector<double>& q_measured,
|
||||
const std::vector<double>& qd_measured,
|
||||
std::vector<double>& qd_command,
|
||||
FrameType frame) override;
|
||||
|
||||
bool updateSpeedLAcceleration(double acceleration) override;
|
||||
bool updateSpeedLLimits(const SpeedLOptions& options) override;
|
||||
bool captureSpeedLReference(const std::vector<double>& q, const CartesianVelocity& target,
|
||||
FrameType frame, SpeedLReference& reference) override;
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override;
|
||||
|
||||
private:
|
||||
bool refreshJointAccelerationLimits_();
|
||||
Eigen::VectorXd applyJointAccelerationLimits_(const Eigen::VectorXd& qdot,
|
||||
const Eigen::VectorXd& reference,
|
||||
double dt) const;
|
||||
bool checkMoveLPlanLineDeviation_(const Eigen::Vector3d& p_start,
|
||||
const Eigen::Vector3d& line_direction,
|
||||
const Eigen::Vector3d& p_current,
|
||||
double traveled,
|
||||
bool& deviation_warned,
|
||||
bool& direction_warned,
|
||||
std::string& stop_reason) const;
|
||||
bool checkMoveLPlanJointContinuity_(const Eigen::VectorXd& q_current,
|
||||
const Eigen::VectorXd& q_next,
|
||||
const Eigen::VectorXd& qdot,
|
||||
const Eigen::VectorXd& prev_qdot,
|
||||
double dt,
|
||||
double path_position,
|
||||
std::string& stop_reason) const;
|
||||
bool checkMoveLPlanJointPositionLimits_(const Eigen::VectorXd& q_current,
|
||||
const Eigen::VectorXd& q_next,
|
||||
const Eigen::VectorXd& qdot,
|
||||
double dt,
|
||||
double path_position,
|
||||
std::string& stop_reason) const;
|
||||
bool checkMoveLPlanCartesianStepFeasibility_(
|
||||
const Eigen::Matrix<double, 6, 1>& desired_twist,
|
||||
const Eigen::Matrix<double, 6, 1>& achieved_twist,
|
||||
double path_position,
|
||||
std::string& stop_reason) const;
|
||||
bool updateAndValidateSpeedLLineDeviation_(const std::vector<double>& q_measured,
|
||||
bool is_stop_command,
|
||||
const Eigen::Vector3d& command_linear_base);
|
||||
bool validateSpeedLJointVelocityCommand_(const Eigen::VectorXd& qdot,
|
||||
const Eigen::VectorXd& reference,
|
||||
double dt) const;
|
||||
bool validateSpeedLPredictedJointPositionLimits_(const std::vector<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::MoveLPlannerConfig movel_config_{};
|
||||
config::SpeedLPlannerConfig speedl_config_{};
|
||||
cmvr::CartesianTwistLimiter twist_limiter_{};
|
||||
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()};
|
||||
Eigen::Vector3d speedl_line_start_tcp_base_{Eigen::Vector3d::Zero()};
|
||||
Eigen::Vector3d speedl_line_direction_base_{Eigen::Vector3d::Zero()};
|
||||
double speedl_applied_acceleration_{0.25};
|
||||
double speedl_applied_angular_acceleration_{0.25};
|
||||
double speedl_applied_linear_jerk_{-1.0};
|
||||
bool speedl_line_check_active_{false};
|
||||
bool speedl_line_deviation_warned_{false};
|
||||
bool speedl_line_direction_warned_{false};
|
||||
|
||||
// speedL 是否已经进入停止阶段。
|
||||
// 停止阶段不要每 1 ms 用 measured twist 重新点燃 Cartesian planner。
|
||||
bool speedl_stop_active_{false};
|
||||
|
||||
bool speedl_configured_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,213 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
|
||||
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h"
|
||||
#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h"
|
||||
#include "common/io/proto_file_io.h"
|
||||
#include "common/math/transform_math.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
constexpr double kDt = .001;
|
||||
using Twist = Eigen::Matrix<double, 6, 1>;
|
||||
|
||||
// Exercise the production planner and real URDF kinematics, without motor I/O.
|
||||
class PinocchioSpeedLLimits : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR);
|
||||
config::ArmRootConfig arms;
|
||||
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(
|
||||
(root / "cmvr-es/config/devices/arm/arm.pb.txt").string(), &arms));
|
||||
ASSERT_GT(arms.arm().robot_arms_size(), 0);
|
||||
auto ik = arms.arm().robot_arms(0).kinematics().pinocchio_dls_ik_solver();
|
||||
ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string());
|
||||
solver_ = std::make_shared<PinocchioDlsIKSolver>(ik);
|
||||
ASSERT_TRUE(solver_->init());
|
||||
planner_ = std::make_unique<PinocchioCartesianMotionPlanner>(solver_);
|
||||
limits_.set_linear_velocity_max(.2);
|
||||
limits_.set_linear_acceleration_max(.4);
|
||||
limits_.set_linear_jerk_max(2);
|
||||
limits_.set_angular_velocity_max(1);
|
||||
limits_.set_angular_acceleration_max(.8);
|
||||
limits_.set_angular_jerk_max(4);
|
||||
limits_.set_enforce_joint_acceleration_limits(false);
|
||||
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
|
||||
}
|
||||
|
||||
struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; };
|
||||
Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options,
|
||||
bool angular = false, int steps = 2200, bool legacy_api = false) {
|
||||
Peaks peaks;
|
||||
Twist previous = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
|
||||
Twist previous_acceleration = Twist::Zero();
|
||||
for (int i = 0; i < steps; ++i) {
|
||||
const bool updated = legacy_api
|
||||
? planner_->updateSpeedLAcceleration(options.acceleration)
|
||||
: planner_->updateSpeedLLimits(options);
|
||||
if (!updated || !planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)) {
|
||||
ADD_FAILURE() << "Planning failed at sample " << i;
|
||||
break;
|
||||
}
|
||||
const Twist velocity = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
|
||||
const Twist acceleration = (velocity - previous) / kDt;
|
||||
const Twist jerk = (acceleration - previous_acceleration) / kDt;
|
||||
const int offset = angular ? 3 : 0;
|
||||
peaks.velocity = std::max(peaks.velocity, velocity.segment<3>(offset).norm());
|
||||
peaks.acceleration = std::max(peaks.acceleration, acceleration.segment<3>(offset).norm());
|
||||
peaks.jerk = std::max(peaks.jerk, jerk.segment<3>(offset).norm());
|
||||
previous = velocity;
|
||||
previous_acceleration = acceleration;
|
||||
}
|
||||
return peaks;
|
||||
}
|
||||
|
||||
void expectPeaks(const Peaks& p, double velocity, double acceleration, double jerk) {
|
||||
// These trajectories contain plateaus: limits must be reached, as well
|
||||
// as obeyed, so an unintended smaller cap cannot pass the test.
|
||||
EXPECT_NEAR(p.velocity, velocity, 1e-8);
|
||||
EXPECT_NEAR(p.acceleration, acceleration, 1e-8);
|
||||
EXPECT_NEAR(p.jerk, jerk, 1e-6);
|
||||
}
|
||||
|
||||
std::shared_ptr<PinocchioDlsIKSolver> solver_;
|
||||
std::unique_ptr<PinocchioCartesianMotionPlanner> planner_;
|
||||
config::SpeedLPlannerConfig limits_;
|
||||
const std::vector<double> q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0};
|
||||
const std::vector<double> qd_ = std::vector<double>(7, 0);
|
||||
std::vector<double> command_;
|
||||
};
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, ExcessiveRequestsRespectAllLinearLimits) {
|
||||
SpeedLOptions options;
|
||||
options.acceleration = 60;
|
||||
options.linear_jerk = 60;
|
||||
CartesianVelocity target;
|
||||
target.vx = .6;
|
||||
target.vy = .8;
|
||||
expectPeaks(sample(target, options), .2, .4, 2);
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, LowerRequestsRemainEffective) {
|
||||
SpeedLOptions options;
|
||||
options.acceleration = .15;
|
||||
options.linear_jerk = .8;
|
||||
CartesianVelocity target;
|
||||
target.vy = 1;
|
||||
expectPeaks(sample(target, options), .2, .15, .8);
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, OmittedJerkRestoresArmLimit) {
|
||||
SpeedLOptions options;
|
||||
options.acceleration = .4;
|
||||
options.linear_jerk = .3;
|
||||
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
|
||||
options.linear_jerk.reset();
|
||||
CartesianVelocity target;
|
||||
target.vy = 1;
|
||||
expectPeaks(sample(target, options), .2, .4, 2);
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, LegacyAccelerationAndStopAreCapped) {
|
||||
SpeedLOptions options;
|
||||
options.acceleration = 60;
|
||||
CartesianVelocity target;
|
||||
target.vy = 1;
|
||||
expectPeaks(sample(target, options, false, 1200, true), .2, .4, 2);
|
||||
const auto stop = sample({}, options, false, 1200, true);
|
||||
EXPECT_LE(stop.velocity, .2);
|
||||
EXPECT_NEAR(stop.acceleration, .4, 1e-8);
|
||||
EXPECT_NEAR(stop.jerk, 2, 1e-6);
|
||||
EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-12);
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) {
|
||||
limits_.set_linear_acceleration_max(.2);
|
||||
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
|
||||
SpeedLOptions options;
|
||||
options.acceleration = .3;
|
||||
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
|
||||
// Linear effective acceleration stays at .2, but angular must change.
|
||||
options.acceleration = .6;
|
||||
CartesianVelocity target;
|
||||
target.wy = 2;
|
||||
expectPeaks(sample(target, options, true), 1, .6, 4);
|
||||
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
|
||||
options.acceleration = 60;
|
||||
expectPeaks(sample(target, options, true), 1, .8, 4);
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) {
|
||||
for (double invalid : {0.0, -1.0, std::numeric_limits<double>::infinity(),
|
||||
std::numeric_limits<double>::quiet_NaN()}) {
|
||||
SpeedLOptions options;
|
||||
options.acceleration = invalid;
|
||||
EXPECT_FALSE(planner_->updateSpeedLLimits(options));
|
||||
EXPECT_FALSE(planner_->updateSpeedLAcceleration(invalid));
|
||||
options.acceleration = .3;
|
||||
options.linear_jerk = invalid;
|
||||
EXPECT_FALSE(planner_->updateSpeedLLimits(options));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, StreamingAlignmentOverridesGlobalReversalPolicy) {
|
||||
for (const double jerk : {10.0, 30.0}) {
|
||||
SCOPED_TRACE(jerk);
|
||||
limits_.set_continuous_linear_reversal(true);
|
||||
limits_.set_linear_acceleration_max(5);
|
||||
limits_.set_linear_jerk_max(jerk);
|
||||
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
|
||||
SpeedLOptions options;
|
||||
options.acceleration = .5;
|
||||
CartesianVelocity target;
|
||||
target.vy = .02;
|
||||
sample(target, options, false, 300);
|
||||
ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10);
|
||||
|
||||
// Same acceleration/jerk: the policy override must bypass their cache.
|
||||
options.continuous_linear_reversal = false;
|
||||
double min_speed = .02;
|
||||
double max_error = 0;
|
||||
for (int i = 0; i < 2000; ++i) {
|
||||
const double angle = (i / 20) * .01;
|
||||
target.vx = .02 * std::sin(angle);
|
||||
target.vy = .02 * std::cos(angle);
|
||||
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
|
||||
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
|
||||
const Twist actual = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
|
||||
min_speed = std::min(min_speed, actual.head<3>().norm());
|
||||
max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm());
|
||||
}
|
||||
EXPECT_NEAR(min_speed, .02, 1e-10);
|
||||
EXPECT_LT(max_error, 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(PinocchioSpeedLLimits, ContactReversalStillCrossesZeroAfterStreamingAlignment) {
|
||||
limits_.set_linear_acceleration_max(1);
|
||||
limits_.set_linear_jerk_max(4);
|
||||
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
|
||||
SpeedLOptions options;
|
||||
options.acceleration = 1;
|
||||
options.continuous_linear_reversal = false;
|
||||
CartesianVelocity target;
|
||||
target.vy = .02;
|
||||
sample(target, options, false, 300);
|
||||
ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10);
|
||||
|
||||
options.continuous_linear_reversal = true;
|
||||
target.vy = -.02;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
|
||||
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
|
||||
}
|
||||
EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-10);
|
||||
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
|
||||
EXPECT_LT(planner_->getSpeedLCommandTwistBase().vy, -.0003);
|
||||
}
|
||||
} // namespace
|
||||
} // namespace cmvr::device
|
||||
@ -1,55 +0,0 @@
|
||||
#ifndef CMVR_ES_TWIST_LIMITER_CONFIG_H
|
||||
#define CMVR_ES_TWIST_LIMITER_CONFIG_H
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "common/config/config_files.h"
|
||||
|
||||
namespace cmvr::device::cartesian_motion {
|
||||
|
||||
inline void configureTwistLimiterFromSpeedLConfig(
|
||||
cmvr::CartesianTwistLimiter& limiter,
|
||||
const config::SpeedLPlannerConfig& config)
|
||||
{
|
||||
using cmvr::common::config::positiveOr;
|
||||
|
||||
limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
|
||||
positiveOr(config.linear_acceleration_max(), 5.0),
|
||||
positiveOr(config.linear_jerk_max(), 10.0));
|
||||
limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
|
||||
positiveOr(config.angular_acceleration_max(), 5.0),
|
||||
positiveOr(config.angular_jerk_max(), 12.0));
|
||||
limiter.setLinearTargetReplanThreshold(
|
||||
positiveOr(config.linear_target_replan_threshold(), 1e-4));
|
||||
limiter.setAngularTargetReplanThreshold(
|
||||
positiveOr(config.angular_target_replan_threshold(), 1e-4));
|
||||
limiter.setLinearReverseSwitchPolicy(
|
||||
config.linear_reverse_cos_threshold() != 0.0
|
||||
? config.linear_reverse_cos_threshold()
|
||||
: -0.8660254037844386,
|
||||
positiveOr(config.linear_reverse_switch_speed_threshold(), 1e-3));
|
||||
limiter.setContinuousLinearReversal(!config.has_continuous_linear_reversal() ||
|
||||
config.continuous_linear_reversal());
|
||||
limiter.initialize(Eigen::Matrix<double, 6, 1>::Zero());
|
||||
}
|
||||
|
||||
inline void updateTwistLimiterAcceleration(
|
||||
cmvr::CartesianTwistLimiter& limiter,
|
||||
const config::SpeedLPlannerConfig& config,
|
||||
const double acceleration)
|
||||
{
|
||||
using cmvr::common::config::positiveOr;
|
||||
|
||||
limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
|
||||
std::min(acceleration, positiveOr(config.linear_acceleration_max(), 5.0)),
|
||||
positiveOr(config.linear_jerk_max(), 10.0));
|
||||
limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
|
||||
std::min(acceleration, positiveOr(config.angular_acceleration_max(), 5.0)),
|
||||
positiveOr(config.angular_jerk_max(), 12.0));
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::cartesian_motion
|
||||
|
||||
#endif // CMVR_ES_TWIST_LIMITER_CONFIG_H
|
||||
@ -1,55 +0,0 @@
|
||||
#ifndef CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H
|
||||
#define CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h"
|
||||
#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h"
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class JointMotionPlannerFactory {
|
||||
public:
|
||||
static std::shared_ptr<JointMotionPlanner> create(
|
||||
const config::MoveJConfig& cfg)
|
||||
{
|
||||
if (!cfg.has_toppra_joint_motion_planner()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
cmvr::PathType path_type;
|
||||
switch (cfg.toppra_joint_motion_planner().path_type()) {
|
||||
case config::TOPPRA_PATH_TYPE_LINEAR:
|
||||
path_type = cmvr::PathType::Linear;
|
||||
break;
|
||||
case config::TOPPRA_PATH_TYPE_CUBIC_HERMITE:
|
||||
path_type = cmvr::PathType::CubicHermite;
|
||||
break;
|
||||
case config::TOPPRA_PATH_TYPE_QUINTIC:
|
||||
path_type = cmvr::PathType::Quintic;
|
||||
break;
|
||||
case config::TOPPRA_PATH_TYPE_NATURAL:
|
||||
path_type = cmvr::PathType::Natural;
|
||||
break;
|
||||
case config::TOPPRA_PATH_TYPE_UNKNOWN:
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const auto& toppra = cfg.toppra_joint_motion_planner();
|
||||
auto planner = std::make_shared<ToppraJointMotionPlanner>(
|
||||
path_type,
|
||||
toppra.sample_period_s(),
|
||||
toppra.grid_size(),
|
||||
toppra.high_grid_size());
|
||||
if (!planner->init()) {
|
||||
return nullptr;
|
||||
}
|
||||
return planner;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H
|
||||
@ -1,46 +0,0 @@
|
||||
#ifndef CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H
|
||||
#define CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "../../joint_motion_planner.h"
|
||||
#include "../../../../base_motion/joint_trajectory/joint_trajectory_planner.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class ToppraJointMotionPlanner final : public JointMotionPlanner {
|
||||
public:
|
||||
ToppraJointMotionPlanner(cmvr::PathType path_type,
|
||||
double sample_period_s,
|
||||
int grid_size,
|
||||
int high_grid_size);
|
||||
|
||||
bool init() override;
|
||||
|
||||
bool planMoveJ(const std::vector<double>& start,
|
||||
const JointPositionCommand& target,
|
||||
const MotionOptions& options,
|
||||
double speed_scaling,
|
||||
JointTrajectory& trajectory) override;
|
||||
|
||||
bool planReplay(const std::vector<double>& current_position,
|
||||
const JointTrajectory& recorded_trajectory,
|
||||
const MotionOptions& options,
|
||||
JointTrajectory& replay_trajectory) override;
|
||||
|
||||
private:
|
||||
bool sampleTrajectory_(
|
||||
const std::shared_ptr<cmvr::JointTrajectoryPlanner>& planner,
|
||||
const cmvr::TrajPtr& raw_trajectory,
|
||||
JointTrajectory& trajectory) const;
|
||||
|
||||
std::shared_ptr<cmvr::JointTrajectoryPlanner> planner_;
|
||||
cmvr::PathType path_type_{cmvr::PathType::Quintic};
|
||||
double sample_period_s_{0.001};
|
||||
int grid_size_{150};
|
||||
int high_grid_size_{300};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H
|
||||
@ -1,258 +0,0 @@
|
||||
#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<double> toStdVector(const Eigen::VectorXd& value)
|
||||
{
|
||||
std::vector<double> result;
|
||||
result.reserve(static_cast<std::size_t>(value.size()));
|
||||
for (int i = 0; i < value.size(); ++i) {
|
||||
result.push_back(value[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ToppraJointMotionPlanner::ToppraJointMotionPlanner(const cmvr::PathType path_type,
|
||||
const double sample_period_s,
|
||||
const int grid_size,
|
||||
const int high_grid_size)
|
||||
: path_type_(path_type)
|
||||
, sample_period_s_(sample_period_s)
|
||||
, grid_size_(grid_size)
|
||||
, high_grid_size_(high_grid_size)
|
||||
{
|
||||
}
|
||||
|
||||
bool ToppraJointMotionPlanner::init()
|
||||
{
|
||||
if (sample_period_s_ <= 0.0 || grid_size_ <= 0 || high_grid_size_ < grid_size_) {
|
||||
return false;
|
||||
}
|
||||
planner_ = std::make_shared<cmvr::ToppraJointTrajectoryPlanner>(path_type_);
|
||||
planner_->setGridSizes(grid_size_, high_grid_size_);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ToppraJointMotionPlanner::sampleTrajectory_(
|
||||
const std::shared_ptr<cmvr::JointTrajectoryPlanner>& planner,
|
||||
const cmvr::TrajPtr& raw_trajectory,
|
||||
JointTrajectory& trajectory) const
|
||||
{
|
||||
const auto raw_samples = planner->sampleTrajectory(
|
||||
raw_trajectory, sample_period_s_);
|
||||
if (raw_samples.size() < 2) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] trajectory sampling returned fewer than "
|
||||
"two points: count="
|
||||
<< raw_samples.size();
|
||||
return false;
|
||||
}
|
||||
trajectory.clear();
|
||||
trajectory.reserve(raw_samples.size());
|
||||
for (std::size_t i = 0; i < raw_samples.size(); ++i) {
|
||||
const auto& sample = raw_samples[i];
|
||||
if (!std::isfinite(sample.t) || !sample.q.allFinite() ||
|
||||
!sample.qd.allFinite()) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] sampled trajectory contains "
|
||||
"a non-finite value at point="
|
||||
<< i;
|
||||
trajectory.clear();
|
||||
return false;
|
||||
}
|
||||
JointTrajectoryPoint point;
|
||||
point.time_s = sample.t;
|
||||
point.position = toStdVector(sample.q);
|
||||
point.velocity = toStdVector(sample.qd);
|
||||
trajectory.push_back(std::move(point));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ToppraJointMotionPlanner::planMoveJ(const std::vector<double>& start,
|
||||
const JointPositionCommand& target,
|
||||
const MotionOptions& options,
|
||||
const double speed_scaling,
|
||||
JointTrajectory& trajectory)
|
||||
{
|
||||
trajectory.clear();
|
||||
if (!planner_ || start.empty() || start.size() != target.position.size() ||
|
||||
options.velocity <= 0.0 || options.acceleration <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
cmvr::TrajPtr raw_trajectory;
|
||||
planner_->setPathType(path_type_);
|
||||
planner_->setGridSizes(grid_size_, high_grid_size_);
|
||||
planner_->setSymmetricLimits(
|
||||
std::vector<double>(start.size(), options.velocity * speed_scaling),
|
||||
std::vector<double>(start.size(), options.acceleration));
|
||||
if (!planner_->plan(start, target.position, raw_trajectory)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return sampleTrajectory_(planner_, raw_trajectory, trajectory);
|
||||
}
|
||||
|
||||
bool ToppraJointMotionPlanner::planReplay(
|
||||
const std::vector<double>& current_position,
|
||||
const JointTrajectory& recorded_trajectory,
|
||||
const MotionOptions& options,
|
||||
JointTrajectory& replay_trajectory)
|
||||
{
|
||||
replay_trajectory.clear();
|
||||
if (current_position.empty() || recorded_trajectory.size() < 2 ||
|
||||
options.velocity <= 0.0 ||
|
||||
options.acceleration <= 0.0 || !std::isfinite(options.velocity) ||
|
||||
!std::isfinite(options.acceleration)) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid trajectory or options";
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::size_t dof = current_position.size();
|
||||
if (!options.joint_velocity_limits.empty() &&
|
||||
options.joint_velocity_limits.size() != dof) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid DOF or joint limits";
|
||||
return false;
|
||||
}
|
||||
for (const double position : current_position) {
|
||||
if (!std::isfinite(position)) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite current position";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < recorded_trajectory.size(); ++i) {
|
||||
const auto& point = recorded_trajectory[i];
|
||||
if (!std::isfinite(point.time_s) || point.position.size() != dof ||
|
||||
(i > 0 && point.time_s <= recorded_trajectory[i - 1].time_s)) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid recorded point: "
|
||||
<< i;
|
||||
return false;
|
||||
}
|
||||
for (std::size_t joint = 0; joint < dof; ++joint) {
|
||||
if (!std::isfinite(point.position[joint])) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite recorded point: "
|
||||
<< i;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<double> velocity_limits = options.joint_velocity_limits;
|
||||
if (velocity_limits.empty()) {
|
||||
velocity_limits.assign(dof, options.velocity);
|
||||
}
|
||||
for (std::size_t joint = 0; joint < velocity_limits.size(); ++joint) {
|
||||
const double limit = velocity_limits[joint];
|
||||
if (!std::isfinite(limit) || limit <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid joint velocity limit";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const double ramp_duration_s = std::max(
|
||||
sample_period_s_, options.velocity / options.acceleration);
|
||||
replay_trajectory.reserve(recorded_trajectory.size() + 2);
|
||||
replay_trajectory.push_back(JointTrajectoryPoint{
|
||||
0.0, current_position, std::vector<double>(dof, 0.0)});
|
||||
|
||||
double replay_time_s = ramp_duration_s;
|
||||
replay_trajectory.push_back(JointTrajectoryPoint{
|
||||
replay_time_s,
|
||||
recorded_trajectory.back().position,
|
||||
std::vector<double>(dof, 0.0)});
|
||||
for (std::size_t i = recorded_trajectory.size() - 1; i > 0; --i) {
|
||||
replay_time_s += recorded_trajectory[i].time_s -
|
||||
recorded_trajectory[i - 1].time_s;
|
||||
replay_trajectory.push_back(JointTrajectoryPoint{
|
||||
replay_time_s,
|
||||
recorded_trajectory[i - 1].position,
|
||||
std::vector<double>(dof, 0.0)});
|
||||
}
|
||||
replay_time_s += ramp_duration_s;
|
||||
replay_trajectory.push_back(JointTrajectoryPoint{
|
||||
replay_time_s,
|
||||
recorded_trajectory.front().position,
|
||||
std::vector<double>(dof, 0.0)});
|
||||
|
||||
const auto update_velocities = [&] {
|
||||
for (auto& point : replay_trajectory) {
|
||||
std::fill(point.velocity.begin(), point.velocity.end(), 0.0);
|
||||
}
|
||||
for (std::size_t i = 1; i + 1 < replay_trajectory.size(); ++i) {
|
||||
const double dt = replay_trajectory[i + 1].time_s -
|
||||
replay_trajectory[i - 1].time_s;
|
||||
for (std::size_t joint = 0; joint < dof; ++joint) {
|
||||
replay_trajectory[i].velocity[joint] =
|
||||
(replay_trajectory[i + 1].position[joint] -
|
||||
replay_trajectory[i - 1].position[joint]) / dt;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (int iteration = 0; iteration < 3; ++iteration) {
|
||||
update_velocities();
|
||||
double required_scale = 1.0;
|
||||
std::vector<double> previous_position_velocity(dof, 0.0);
|
||||
for (std::size_t i = 0; i < replay_trajectory.size(); ++i) {
|
||||
const auto& point = replay_trajectory[i];
|
||||
for (std::size_t joint = 0; joint < dof; ++joint) {
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::abs(point.velocity[joint]) / velocity_limits[joint]);
|
||||
if (i == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const double dt = point.time_s -
|
||||
replay_trajectory[i - 1].time_s;
|
||||
const double position_velocity =
|
||||
(point.position[joint] -
|
||||
replay_trajectory[i - 1].position[joint]) / dt;
|
||||
const double acceleration =
|
||||
(point.velocity[joint] -
|
||||
replay_trajectory[i - 1].velocity[joint]) / dt;
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::abs(position_velocity) / velocity_limits[joint]);
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::sqrt(std::abs(acceleration) /
|
||||
options.acceleration));
|
||||
if (i > 1) {
|
||||
const double position_acceleration =
|
||||
(position_velocity -
|
||||
previous_position_velocity[joint]) / dt;
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::sqrt(std::abs(position_acceleration) /
|
||||
options.acceleration));
|
||||
}
|
||||
previous_position_velocity[joint] = position_velocity;
|
||||
}
|
||||
}
|
||||
|
||||
if (required_scale <= 1.0 + 1e-9) {
|
||||
break;
|
||||
}
|
||||
required_scale *= 1.001;
|
||||
for (auto& point : replay_trajectory) {
|
||||
point.time_s *= required_scale;
|
||||
}
|
||||
}
|
||||
update_velocities();
|
||||
if (!validateJointTrajectory(replay_trajectory, dof, options)) {
|
||||
replay_trajectory.clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,139 +0,0 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "joint_motion/toppra/include/toppra_joint_motion_planner.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t kDof = 7;
|
||||
|
||||
JointTrajectory makeRecordedTrajectory(const std::size_t point_count)
|
||||
{
|
||||
JointTrajectory trajectory;
|
||||
trajectory.reserve(point_count);
|
||||
for (std::size_t i = 0; i < point_count; ++i) {
|
||||
const double s = static_cast<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;
|
||||
}
|
||||
|
||||
TEST(ToppraJointMotionPlannerTest, PlansBoundedReverseReplay)
|
||||
{
|
||||
ToppraJointMotionPlanner planner(
|
||||
cmvr::PathType::Quintic, 0.001, 150, 300);
|
||||
ASSERT_TRUE(planner.init());
|
||||
|
||||
const JointTrajectory recorded = makeRecordedTrajectory(300);
|
||||
MotionOptions options;
|
||||
options.velocity = 0.15;
|
||||
options.acceleration = 5.0;
|
||||
|
||||
JointTrajectory replay;
|
||||
ASSERT_TRUE(planner.planReplay(
|
||||
recorded.back().position, recorded, options, replay));
|
||||
ASSERT_EQ(replay.size(), recorded.size() + 2);
|
||||
EXPECT_LT(maximumPositionError(
|
||||
replay.front().position, recorded.back().position),
|
||||
1e-9);
|
||||
EXPECT_LT(maximumPositionError(
|
||||
replay.back().position, recorded.front().position),
|
||||
1e-9);
|
||||
for (std::size_t i = 0; i < recorded.size(); ++i) {
|
||||
EXPECT_LT(maximumPositionError(
|
||||
replay[i + 1].position,
|
||||
recorded[recorded.size() - 1 - i].position),
|
||||
1e-9);
|
||||
}
|
||||
|
||||
double maximum_velocity = 0.0;
|
||||
double maximum_acceleration = 0.0;
|
||||
for (std::size_t i = 0; i < replay.size(); ++i) {
|
||||
ASSERT_EQ(replay[i].position.size(), kDof);
|
||||
ASSERT_EQ(replay[i].velocity.size(), kDof);
|
||||
for (std::size_t joint = 0; joint < kDof; ++joint) {
|
||||
maximum_velocity = std::max(
|
||||
maximum_velocity, std::abs(replay[i].velocity[joint]));
|
||||
if (i > 0) {
|
||||
const double dt = replay[i].time_s - replay[i - 1].time_s;
|
||||
ASSERT_GT(dt, 0.0);
|
||||
maximum_acceleration = std::max(
|
||||
maximum_acceleration,
|
||||
std::abs(replay[i].velocity[joint] -
|
||||
replay[i - 1].velocity[joint]) / dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
EXPECT_LE(maximum_velocity, options.velocity + 1e-6);
|
||||
EXPECT_LE(maximum_acceleration, options.acceleration + 1e-3);
|
||||
}
|
||||
|
||||
TEST(ToppraJointMotionPlannerTest, RejectsNonIncreasingRecordedTime)
|
||||
{
|
||||
ToppraJointMotionPlanner planner(
|
||||
cmvr::PathType::Quintic, 0.001, 150, 300);
|
||||
ASSERT_TRUE(planner.init());
|
||||
|
||||
JointTrajectory recorded = makeRecordedTrajectory(10);
|
||||
recorded[5].time_s = recorded[4].time_s;
|
||||
MotionOptions options;
|
||||
options.velocity = 0.15;
|
||||
options.acceleration = 5.0;
|
||||
|
||||
JointTrajectory replay;
|
||||
EXPECT_FALSE(planner.planReplay(
|
||||
recorded.back().position, recorded, options, replay));
|
||||
EXPECT_TRUE(replay.empty());
|
||||
}
|
||||
|
||||
TEST(ToppraJointMotionPlannerTest, ValidationRejectsInvalidOutputTrajectory)
|
||||
{
|
||||
ToppraJointMotionPlanner planner(
|
||||
cmvr::PathType::Quintic, 0.001, 150, 300);
|
||||
MotionOptions options;
|
||||
options.velocity = 0.15;
|
||||
options.acceleration = 5.0;
|
||||
|
||||
JointTrajectory trajectory = makeRecordedTrajectory(10);
|
||||
trajectory[5].velocity[2] = options.velocity + 0.01;
|
||||
EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options));
|
||||
|
||||
trajectory[5].velocity[2] = 0.0;
|
||||
trajectory[5].time_s = trajectory[4].time_s;
|
||||
EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr::device
|
||||
@ -1,49 +0,0 @@
|
||||
|
||||
|
||||
add_library(base_motion SHARED
|
||||
joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp
|
||||
|
||||
motion_profile/s_curve/src/s_curve.cpp
|
||||
motion_profile/s_curve/src/s_curve_position_planner.cpp
|
||||
motion_profile/s_curve/src/s_curve_velocity_planner.cpp
|
||||
cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp
|
||||
)
|
||||
|
||||
target_include_directories(base_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_link_libraries(base_motion PUBLIC
|
||||
OsqpEigen
|
||||
tinyxml2
|
||||
fcl
|
||||
toppra
|
||||
cmvr_es::common
|
||||
)
|
||||
|
||||
add_library(cmvr_es::base_motion ALIAS base_motion)
|
||||
add_executable(cartesian_twist_limiter_reversal_test
|
||||
cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp)
|
||||
target_link_libraries(cartesian_twist_limiter_reversal_test PRIVATE
|
||||
cmvr_es::base_motion gtest gtest_main)
|
||||
install(TARGETS base_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(toppra_multi_waypoint_test
|
||||
joint_trajectory/toppra/test/toppra_multi_waypoint_test.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(toppra_multi_waypoint_test
|
||||
PRIVATE
|
||||
cmvr_es::base_motion
|
||||
gtest
|
||||
gtest_main
|
||||
)
|
||||
|
||||
add_executable(s_curve_velocity_planner_stop_test
|
||||
motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(s_curve_velocity_planner_stop_test
|
||||
PRIVATE
|
||||
cmvr_es::base_motion
|
||||
gtest
|
||||
gtest_main
|
||||
)
|
||||
@ -1,249 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Eigen/Core>
|
||||
#include <Eigen/Geometry>
|
||||
#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h"
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
enum class CartesianFrame
|
||||
{
|
||||
Base = 0,
|
||||
Tool = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 6维末端 twist 在线限幅器(基于 SCurveVelocityPlanner1D)
|
||||
*
|
||||
* 线速度部分:
|
||||
* - 固定轴上的有符号速度使用 SCurveVelocityPlanner1D 做 jerk-limited 规划
|
||||
* - 同轴反向连续过零,保留加速度;可显式选择旧的停止后换向策略
|
||||
* - 运动中锁定当前方向,不做方向插值
|
||||
* - 若目标方向与当前方向不共线,则采用“先减速到0,再切方向”的 switch policy
|
||||
*
|
||||
* 角速度部分:
|
||||
* - 与线速度独立
|
||||
* - 模长使用 SCurveVelocityPlanner1D 做 jerk-limited 速度规划
|
||||
* - 运动中锁定当前旋转轴,不做方向插值
|
||||
*
|
||||
* 接口语义:
|
||||
* - setTargetTwist(...):设置目标 twist
|
||||
* - synchronizeToMeasuredTwistBase(...):用测量 twist 同步当前状态
|
||||
* - update(dt, base_R_tool):根据当前目标与当前状态生成下一拍命令 twist
|
||||
*/
|
||||
class CartesianTwistLimiter
|
||||
{
|
||||
public:
|
||||
using Twist = Eigen::Matrix<double, 6, 1>;
|
||||
|
||||
CartesianTwistLimiter();
|
||||
|
||||
void setLinearConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
|
||||
void setAngularConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
|
||||
void setLinearTargetReplanThreshold(double threshold);
|
||||
void setAngularTargetReplanThreshold(double threshold);
|
||||
|
||||
/**
|
||||
* @brief 设置线速度方向最大转动角速度(rad/s)
|
||||
*/
|
||||
void setLinearDirectionRateLimit(double max_rate_rad_s);
|
||||
|
||||
/**
|
||||
* @brief 设置角速度方向最大转动角速度(rad/s)
|
||||
*/
|
||||
void setAngularDirectionRateLimit(double max_rate_rad_s);
|
||||
|
||||
/**
|
||||
* @brief 设置线速度反向切换策略
|
||||
*
|
||||
* @param cos_threshold 近反向判定阈值,范围 [-1, 1]
|
||||
* @param switch_speed_threshold 线速度模长低于该阈值后,允许切到目标方向
|
||||
*/
|
||||
void setLinearReverseSwitchPolicy(double cos_threshold,
|
||||
double switch_speed_threshold);
|
||||
|
||||
// Same-axis reversal uses a signed velocity without resetting acceleration
|
||||
// at zero. Disable for streaming direction tracking (e.g. visual alignment).
|
||||
void setContinuousLinearReversal(bool enabled);
|
||||
bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; }
|
||||
|
||||
/**
|
||||
* @brief 初始化当前 twist 状态
|
||||
*
|
||||
* 注意:
|
||||
* - 初始 twist 视为 base 坐标系下
|
||||
*/
|
||||
void initialize(const Twist& initial_twist = Twist::Zero());
|
||||
|
||||
void reset();
|
||||
|
||||
/**
|
||||
* @brief 设置目标 twist
|
||||
*
|
||||
* @param target_twist 目标 twist
|
||||
* @param frame 输入目标的坐标系(Base 或 Tool)
|
||||
*/
|
||||
void setTargetTwist(const Twist& target_twist, CartesianFrame frame);
|
||||
|
||||
/**
|
||||
* @brief 平滑停下
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* @brief 急停
|
||||
*
|
||||
* 使用更大的减速度/jerk 约束把当前线速度/角速度平滑拉回 0。
|
||||
* 当前运动停止后,会自动恢复到常规约束。
|
||||
*
|
||||
* @param emergency_acceleration 急停减速度幅值
|
||||
* @param emergency_jerk 急停 jerk 幅值
|
||||
*/
|
||||
void emergencyStop(double emergency_acceleration,
|
||||
double emergency_jerk);
|
||||
|
||||
/**
|
||||
* @brief 急停(分别指定线速度/角速度减速度与 jerk)
|
||||
*
|
||||
* @param emergency_linear_acceleration 线速度急停减速度幅值
|
||||
* @param emergency_linear_jerk 线速度急停 jerk 幅值
|
||||
* @param emergency_angular_acceleration 角速度急停减速度幅值
|
||||
* @param emergency_angular_jerk 角速度急停 jerk 幅值
|
||||
*/
|
||||
void emergencyStop(double emergency_linear_acceleration,
|
||||
double emergency_linear_jerk,
|
||||
double emergency_angular_acceleration,
|
||||
double emergency_angular_jerk);
|
||||
|
||||
/**
|
||||
* @brief 用测得的 base-frame twist 同步当前状态
|
||||
*
|
||||
* 作用:
|
||||
* - 更新当前执行方向
|
||||
* - 线速度使用固定轴投影(保留正负号),角速度使用模长
|
||||
* - keep_target=true 时:
|
||||
* - 若测量状态仍贴着当前 profile,则保持当前 profile
|
||||
* - 否则由 planner 内部从测量状态重规划到当前目标
|
||||
* - keep_target=false 时:
|
||||
* - 清掉旧 profile,仅覆盖状态
|
||||
*
|
||||
* @param measured_twist_base 当前测得实际 twist(base 系)
|
||||
* @param dt 与上一次测量同步的时间间隔
|
||||
* @param keep_target 是否保留当前目标模长
|
||||
*/
|
||||
void synchronize(const Twist& measured_twist_base,
|
||||
double dt,
|
||||
bool keep_target = true);
|
||||
|
||||
/**
|
||||
* @brief 更新一步,返回 base 坐标系下的执行 twist 命令
|
||||
*/
|
||||
Twist update(double dt, const Eigen::Matrix3d& base_R_tool);
|
||||
|
||||
const Twist& getTwistBase() const { return twist_base_; }
|
||||
const Twist& getCommandedTwistBase() const { return twist_base_; }
|
||||
const Twist& getTargetTwistBase() const { return target_twist_base_; }
|
||||
const Twist& getAccelerationBase() const { return acceleration_base_; }
|
||||
const Twist& getJerkBase() const { return jerk_base_; }
|
||||
|
||||
bool isMoving() const;
|
||||
|
||||
private:
|
||||
static constexpr double EPSILON = 1e-12;
|
||||
static constexpr double DEFAULT_LINEAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s
|
||||
static constexpr double DEFAULT_ANGULAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s
|
||||
static constexpr double DEFAULT_LINEAR_REVERSE_COS_THRESHOLD = -0.8660254037844386; // cos(150 deg)
|
||||
static constexpr double DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD = 1e-3;
|
||||
static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999;
|
||||
static constexpr double DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD = 1e-3;
|
||||
|
||||
// 模长 planner
|
||||
SCurveVelocityPlanner1D linear_norm_planner_;
|
||||
SCurveVelocityPlanner1D angular_norm_planner_;
|
||||
|
||||
// 常规约束缓存。急停结束后恢复到这里。
|
||||
double linear_max_velocity_;
|
||||
double linear_max_acceleration_;
|
||||
double linear_max_jerk_;
|
||||
double angular_max_velocity_;
|
||||
double angular_max_acceleration_;
|
||||
double angular_max_jerk_;
|
||||
|
||||
// 方向变化率限制(rad/s)
|
||||
double linear_direction_rate_limit_;
|
||||
double angular_direction_rate_limit_;
|
||||
|
||||
// 线速度 reverse policy
|
||||
double linear_reverse_cos_threshold_;
|
||||
double linear_reverse_switch_speed_threshold_;
|
||||
double angular_switch_speed_threshold_;
|
||||
bool emergency_stop_active_;
|
||||
bool continuous_linear_reversal_{true};
|
||||
|
||||
// 目标/当前状态
|
||||
Twist target_twist_input_;
|
||||
Twist target_twist_base_;
|
||||
|
||||
Twist twist_base_;
|
||||
Twist acceleration_base_;
|
||||
Twist jerk_base_;
|
||||
|
||||
Twist prev_twist_base_;
|
||||
Twist prev_acceleration_base_;
|
||||
|
||||
CartesianFrame input_frame_;
|
||||
|
||||
// 当前执行方向
|
||||
Eigen::Vector3d current_linear_dir_base_;
|
||||
Eigen::Vector3d current_angular_dir_base_;
|
||||
|
||||
// 最近一次非零目标方向(目标变0时用于平滑停下)
|
||||
Eigen::Vector3d last_target_linear_dir_base_;
|
||||
Eigen::Vector3d last_target_angular_dir_base_;
|
||||
|
||||
// 测量同步用缓存
|
||||
bool has_measured_sync_;
|
||||
Twist last_measured_twist_base_;
|
||||
Twist last_measured_acceleration_base_;
|
||||
double prev_measured_linear_norm_;
|
||||
double prev_measured_angular_norm_;
|
||||
|
||||
static Twist transformTwistToolToBase(const Twist& twist_tool,
|
||||
const Eigen::Matrix3d& base_R_tool);
|
||||
|
||||
static Eigen::Vector3d chooseDirection(const Eigen::Vector3d& target_vec,
|
||||
const Eigen::Vector3d& fallback);
|
||||
|
||||
static Eigen::Vector3d rotateDirectionToward(const Eigen::Vector3d& current_dir,
|
||||
const Eigen::Vector3d& target_dir,
|
||||
double max_rate_rad_s,
|
||||
double dt);
|
||||
|
||||
static Eigen::Vector3d rotateAroundAxis(const Eigen::Vector3d& v,
|
||||
const Eigen::Vector3d& axis_unit,
|
||||
double angle_rad);
|
||||
|
||||
static Eigen::Vector3d chooseOrthogonalUnit(const Eigen::Vector3d& v);
|
||||
|
||||
void applyLinearConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
void applyAngularConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk);
|
||||
void restoreNominalConstraints();
|
||||
static bool isZeroTwist(const Twist& twist);
|
||||
|
||||
static double clamp(double value, double lo, double hi)
|
||||
{
|
||||
return std::max(lo, std::min(hi, value));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,573 +0,0 @@
|
||||
#include "../include/cartesian_twist_limiter.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
CartesianTwistLimiter::CartesianTwistLimiter()
|
||||
: linear_norm_planner_(1.0, 1.0, 5.0)
|
||||
, angular_norm_planner_(1.0, 1.0, 5.0)
|
||||
, linear_max_velocity_(1.0)
|
||||
, linear_max_acceleration_(1.0)
|
||||
, linear_max_jerk_(5.0)
|
||||
, angular_max_velocity_(1.0)
|
||||
, angular_max_acceleration_(1.0)
|
||||
, angular_max_jerk_(5.0)
|
||||
, linear_direction_rate_limit_(DEFAULT_LINEAR_DIR_RATE_LIMIT)
|
||||
, angular_direction_rate_limit_(DEFAULT_ANGULAR_DIR_RATE_LIMIT)
|
||||
, linear_reverse_cos_threshold_(DEFAULT_LINEAR_REVERSE_COS_THRESHOLD)
|
||||
, linear_reverse_switch_speed_threshold_(DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD)
|
||||
, angular_switch_speed_threshold_(DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD)
|
||||
, emergency_stop_active_(false)
|
||||
, target_twist_input_(Twist::Zero())
|
||||
, target_twist_base_(Twist::Zero())
|
||||
, twist_base_(Twist::Zero())
|
||||
, acceleration_base_(Twist::Zero())
|
||||
, jerk_base_(Twist::Zero())
|
||||
, prev_twist_base_(Twist::Zero())
|
||||
, prev_acceleration_base_(Twist::Zero())
|
||||
, input_frame_(CartesianFrame::Base)
|
||||
, current_linear_dir_base_(Eigen::Vector3d::Zero())
|
||||
, current_angular_dir_base_(Eigen::Vector3d::Zero())
|
||||
, last_target_linear_dir_base_(Eigen::Vector3d::Zero())
|
||||
, last_target_angular_dir_base_(Eigen::Vector3d::Zero())
|
||||
, has_measured_sync_(false)
|
||||
, last_measured_twist_base_(Twist::Zero())
|
||||
, last_measured_acceleration_base_(Twist::Zero())
|
||||
, prev_measured_linear_norm_(0.0)
|
||||
, prev_measured_angular_norm_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::applyLinearConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
linear_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::applyAngularConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
angular_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setLinearConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
linear_max_velocity_ = std::abs(max_velocity);
|
||||
linear_max_acceleration_ = std::abs(max_acceleration);
|
||||
linear_max_jerk_ = std::abs(max_jerk);
|
||||
|
||||
if (!emergency_stop_active_) {
|
||||
applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_);
|
||||
}
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setAngularConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
angular_max_velocity_ = std::abs(max_velocity);
|
||||
angular_max_acceleration_ = std::abs(max_acceleration);
|
||||
angular_max_jerk_ = std::abs(max_jerk);
|
||||
|
||||
if (!emergency_stop_active_) {
|
||||
applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_);
|
||||
}
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setLinearTargetReplanThreshold(double threshold)
|
||||
{
|
||||
linear_norm_planner_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setAngularTargetReplanThreshold(double threshold)
|
||||
{
|
||||
angular_norm_planner_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setLinearDirectionRateLimit(double max_rate_rad_s)
|
||||
{
|
||||
linear_direction_rate_limit_ = std::max(0.0, max_rate_rad_s);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setAngularDirectionRateLimit(double max_rate_rad_s)
|
||||
{
|
||||
angular_direction_rate_limit_ = std::max(0.0, max_rate_rad_s);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setLinearReverseSwitchPolicy(double cos_threshold,
|
||||
double switch_speed_threshold)
|
||||
{
|
||||
linear_reverse_cos_threshold_ = clamp(cos_threshold, -1.0, 1.0);
|
||||
linear_reverse_switch_speed_threshold_ = std::max(0.0, switch_speed_threshold);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setContinuousLinearReversal(bool enabled)
|
||||
{
|
||||
if (continuous_linear_reversal_ == enabled) return;
|
||||
|
||||
if (!enabled) {
|
||||
const double velocity = linear_norm_planner_.getVelocity();
|
||||
const double acceleration = linear_norm_planner_.getAcceleration();
|
||||
// The streaming policy stores a speed magnitude and a physical direction.
|
||||
// Convert a negative signed state without reversing its physical motion or
|
||||
// dropping its acceleration when a command changes policy mid-retraction.
|
||||
if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) {
|
||||
current_linear_dir_base_ = -current_linear_dir_base_;
|
||||
linear_norm_planner_.overwriteState(-velocity, -acceleration, false);
|
||||
prev_measured_linear_norm_ = -prev_measured_linear_norm_;
|
||||
}
|
||||
}
|
||||
continuous_linear_reversal_ = enabled;
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::initialize(const Twist& initial_twist)
|
||||
{
|
||||
restoreNominalConstraints();
|
||||
emergency_stop_active_ = false;
|
||||
|
||||
const Eigen::Vector3d v0 = initial_twist.head<3>();
|
||||
const Eigen::Vector3d w0 = initial_twist.tail<3>();
|
||||
|
||||
const double v0_norm = v0.norm();
|
||||
const double w0_norm = w0.norm();
|
||||
|
||||
linear_norm_planner_.initialize(v0_norm, 0.0);
|
||||
angular_norm_planner_.initialize(w0_norm, 0.0);
|
||||
|
||||
target_twist_input_ = initial_twist;
|
||||
target_twist_base_ = initial_twist;
|
||||
twist_base_ = initial_twist;
|
||||
acceleration_base_.setZero();
|
||||
jerk_base_.setZero();
|
||||
prev_twist_base_ = initial_twist;
|
||||
prev_acceleration_base_.setZero();
|
||||
|
||||
// current_linear_dir_base_ =
|
||||
// (v0_norm > EPSILON) ? (v0 / v0_norm) : Eigen::Vector3d::Zero();
|
||||
// current_angular_dir_base_ =
|
||||
// (w0_norm > EPSILON) ? (w0 / w0_norm) : Eigen::Vector3d::Zero();
|
||||
current_linear_dir_base_.setZero();
|
||||
current_angular_dir_base_.setZero();
|
||||
if (v0_norm > EPSILON) {
|
||||
current_linear_dir_base_ = v0 / v0_norm;
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
if (w0_norm > EPSILON) {
|
||||
current_angular_dir_base_ = w0 / w0_norm;
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
last_target_linear_dir_base_ = current_linear_dir_base_;
|
||||
last_target_angular_dir_base_ = current_angular_dir_base_;
|
||||
|
||||
has_measured_sync_ = false;
|
||||
last_measured_twist_base_ = initial_twist;
|
||||
last_measured_acceleration_base_.setZero();
|
||||
prev_measured_linear_norm_ = v0_norm;
|
||||
prev_measured_angular_norm_ = w0_norm;
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::reset()
|
||||
{
|
||||
restoreNominalConstraints();
|
||||
emergency_stop_active_ = false;
|
||||
|
||||
linear_norm_planner_.reset();
|
||||
angular_norm_planner_.reset();
|
||||
|
||||
target_twist_input_.setZero();
|
||||
target_twist_base_.setZero();
|
||||
twist_base_.setZero();
|
||||
acceleration_base_.setZero();
|
||||
jerk_base_.setZero();
|
||||
prev_twist_base_.setZero();
|
||||
prev_acceleration_base_.setZero();
|
||||
|
||||
input_frame_ = CartesianFrame::Base;
|
||||
|
||||
current_linear_dir_base_.setZero();
|
||||
current_angular_dir_base_.setZero();
|
||||
last_target_linear_dir_base_.setZero();
|
||||
last_target_angular_dir_base_.setZero();
|
||||
|
||||
has_measured_sync_ = false;
|
||||
last_measured_twist_base_.setZero();
|
||||
last_measured_acceleration_base_.setZero();
|
||||
prev_measured_linear_norm_ = 0.0;
|
||||
prev_measured_angular_norm_ = 0.0;
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::setTargetTwist(const Twist& target_twist, CartesianFrame frame)
|
||||
{
|
||||
if (emergency_stop_active_ && !isZeroTwist(target_twist)) {
|
||||
restoreNominalConstraints();
|
||||
emergency_stop_active_ = false;
|
||||
}
|
||||
|
||||
target_twist_input_ = target_twist;
|
||||
input_frame_ = frame;
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::stop()
|
||||
{
|
||||
// target_twist_input_.setZero();
|
||||
target_twist_input_.setZero();
|
||||
target_twist_base_.setZero();
|
||||
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
angular_norm_planner_.setTargetVelocity(0.0);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::emergencyStop(double emergency_acceleration,
|
||||
double emergency_jerk)
|
||||
{
|
||||
emergencyStop(emergency_acceleration,
|
||||
emergency_jerk,
|
||||
emergency_acceleration,
|
||||
emergency_jerk);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::emergencyStop(double emergency_linear_acceleration,
|
||||
double emergency_linear_jerk,
|
||||
double emergency_angular_acceleration,
|
||||
double emergency_angular_jerk)
|
||||
{
|
||||
const double linear_stop_acceleration =
|
||||
std::max(std::abs(emergency_linear_acceleration), linear_max_acceleration_);
|
||||
const double linear_stop_jerk =
|
||||
std::max(std::abs(emergency_linear_jerk), linear_max_jerk_);
|
||||
const double angular_stop_acceleration =
|
||||
std::max(std::abs(emergency_angular_acceleration), angular_max_acceleration_);
|
||||
const double angular_stop_jerk =
|
||||
std::max(std::abs(emergency_angular_jerk), angular_max_jerk_);
|
||||
|
||||
applyLinearConstraints(linear_max_velocity_, linear_stop_acceleration, linear_stop_jerk);
|
||||
applyAngularConstraints(angular_max_velocity_, angular_stop_acceleration, angular_stop_jerk);
|
||||
|
||||
emergency_stop_active_ = true;
|
||||
target_twist_input_.setZero();
|
||||
target_twist_base_.setZero();
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
angular_norm_planner_.setTargetVelocity(0.0);
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::synchronize(const Twist& measured_twist_base,
|
||||
double dt,
|
||||
bool keep_target)
|
||||
{
|
||||
const Eigen::Vector3d v_meas = measured_twist_base.head<3>();
|
||||
const Eigen::Vector3d w_meas = measured_twist_base.tail<3>();
|
||||
|
||||
const bool signed_linear = continuous_linear_reversal_ && current_linear_dir_base_.norm() > EPSILON;
|
||||
const double v_norm = signed_linear ? v_meas.dot(current_linear_dir_base_) : v_meas.norm();
|
||||
const double w_norm = w_meas.norm();
|
||||
|
||||
double v_acc = 0.0;
|
||||
double w_acc = 0.0;
|
||||
|
||||
if (dt > EPSILON && has_measured_sync_) {
|
||||
v_acc = (v_norm - prev_measured_linear_norm_) / dt;
|
||||
w_acc = (w_norm - prev_measured_angular_norm_) / dt;
|
||||
|
||||
acceleration_base_ = (measured_twist_base - last_measured_twist_base_) / dt;
|
||||
jerk_base_ = (acceleration_base_ - last_measured_acceleration_base_) / dt;
|
||||
last_measured_acceleration_base_ = acceleration_base_;
|
||||
} else {
|
||||
acceleration_base_.setZero();
|
||||
jerk_base_.setZero();
|
||||
last_measured_acceleration_base_.setZero();
|
||||
}
|
||||
|
||||
prev_measured_linear_norm_ = v_norm;
|
||||
prev_measured_angular_norm_ = w_norm;
|
||||
last_measured_twist_base_ = measured_twist_base;
|
||||
has_measured_sync_ = true;
|
||||
|
||||
// 线速度按固定轴投影保留正负号;角速度仍按模长同步 planner。
|
||||
// keep_target=true:
|
||||
// - 若测量值仍贴着当前 profile,则继续沿旧 profile 走
|
||||
// - 否则从测量状态重规划到当前目标
|
||||
// keep_target=false:
|
||||
// - 仅覆盖状态并清掉旧 profile,不保留当前目标
|
||||
if (keep_target) {
|
||||
linear_norm_planner_.synchronizeAndReplan(v_norm, v_acc);
|
||||
angular_norm_planner_.synchronizeAndReplan(w_norm, w_acc);
|
||||
} else {
|
||||
linear_norm_planner_.overwriteState(v_norm, v_acc, false);
|
||||
angular_norm_planner_.overwriteState(w_norm, w_acc, false);
|
||||
target_twist_input_.setZero();
|
||||
target_twist_base_.setZero();
|
||||
}
|
||||
|
||||
if (!signed_linear && v_norm > EPSILON) {
|
||||
current_linear_dir_base_ = v_meas / v_norm;
|
||||
last_target_linear_dir_base_ = current_linear_dir_base_;
|
||||
}
|
||||
|
||||
if (w_norm > EPSILON) {
|
||||
current_angular_dir_base_ = w_meas / w_norm;
|
||||
last_target_angular_dir_base_ = current_angular_dir_base_;
|
||||
}
|
||||
|
||||
twist_base_ = measured_twist_base;
|
||||
prev_twist_base_ = measured_twist_base;
|
||||
prev_acceleration_base_ = acceleration_base_;
|
||||
}
|
||||
|
||||
CartesianTwistLimiter::Twist
|
||||
CartesianTwistLimiter::transformTwistToolToBase(const Twist& twist_tool,
|
||||
const Eigen::Matrix3d& base_R_tool)
|
||||
{
|
||||
Twist twist_base;
|
||||
twist_base.head<3>() = base_R_tool * twist_tool.head<3>();
|
||||
twist_base.tail<3>() = base_R_tool * twist_tool.tail<3>();
|
||||
return twist_base;
|
||||
}
|
||||
|
||||
Eigen::Vector3d CartesianTwistLimiter::chooseDirection(const Eigen::Vector3d& target_vec,
|
||||
const Eigen::Vector3d& fallback)
|
||||
{
|
||||
const double n = target_vec.norm();
|
||||
if (n > EPSILON) {
|
||||
return target_vec / n;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
Eigen::Vector3d CartesianTwistLimiter::rotateAroundAxis(const Eigen::Vector3d& v,
|
||||
const Eigen::Vector3d& axis_unit,
|
||||
double angle_rad)
|
||||
{
|
||||
const double c = std::cos(angle_rad);
|
||||
const double s = std::sin(angle_rad);
|
||||
return c * v + s * (axis_unit.cross(v)) + (1.0 - c) * axis_unit.dot(v) * axis_unit;
|
||||
}
|
||||
|
||||
Eigen::Vector3d CartesianTwistLimiter::chooseOrthogonalUnit(const Eigen::Vector3d& v)
|
||||
{
|
||||
Eigen::Vector3d ref;
|
||||
if (std::abs(v.x()) < 0.8) {
|
||||
ref = Eigen::Vector3d::UnitX();
|
||||
} else if (std::abs(v.y()) < 0.8) {
|
||||
ref = Eigen::Vector3d::UnitY();
|
||||
} else {
|
||||
ref = Eigen::Vector3d::UnitZ();
|
||||
}
|
||||
|
||||
Eigen::Vector3d ortho = ref - ref.dot(v) * v;
|
||||
const double n = ortho.norm();
|
||||
if (n > EPSILON) {
|
||||
return ortho / n;
|
||||
}
|
||||
return Eigen::Vector3d::UnitX();
|
||||
}
|
||||
|
||||
void CartesianTwistLimiter::restoreNominalConstraints()
|
||||
{
|
||||
applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_);
|
||||
applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_);
|
||||
}
|
||||
|
||||
bool CartesianTwistLimiter::isZeroTwist(const Twist& twist)
|
||||
{
|
||||
return twist.head<3>().squaredNorm() <= EPSILON && twist.tail<3>().squaredNorm() <= EPSILON;
|
||||
}
|
||||
|
||||
Eigen::Vector3d CartesianTwistLimiter::rotateDirectionToward(const Eigen::Vector3d& current_dir,
|
||||
const Eigen::Vector3d& target_dir,
|
||||
double max_rate_rad_s,
|
||||
double dt)
|
||||
{
|
||||
if (dt <= 0.0) {
|
||||
return current_dir;
|
||||
}
|
||||
|
||||
const double cur_n = current_dir.norm();
|
||||
const double tgt_n = target_dir.norm();
|
||||
|
||||
if (tgt_n <= EPSILON) {
|
||||
return current_dir;
|
||||
}
|
||||
if (cur_n <= EPSILON) {
|
||||
return target_dir;
|
||||
}
|
||||
|
||||
const Eigen::Vector3d u = current_dir / cur_n;
|
||||
const Eigen::Vector3d v = target_dir / tgt_n;
|
||||
|
||||
const double dot_uv = clamp(u.dot(v), -1.0, 1.0);
|
||||
const double angle = std::acos(dot_uv);
|
||||
|
||||
if (angle <= 1e-9) {
|
||||
return v;
|
||||
}
|
||||
|
||||
const double max_step = std::max(0.0, max_rate_rad_s) * dt;
|
||||
if (max_step <= 0.0) {
|
||||
return u;
|
||||
}
|
||||
if (angle <= max_step) {
|
||||
return v;
|
||||
}
|
||||
|
||||
Eigen::Vector3d axis = u.cross(v);
|
||||
const double axis_n = axis.norm();
|
||||
|
||||
if (axis_n > EPSILON) {
|
||||
axis /= axis_n;
|
||||
return rotateAroundAxis(u, axis, max_step).normalized();
|
||||
}
|
||||
|
||||
if (dot_uv > 0.0) {
|
||||
return v;
|
||||
}
|
||||
|
||||
const Eigen::Vector3d ortho_axis = chooseOrthogonalUnit(u);
|
||||
return rotateAroundAxis(u, ortho_axis, max_step).normalized();
|
||||
}
|
||||
|
||||
CartesianTwistLimiter::Twist
|
||||
CartesianTwistLimiter::update(double dt, const Eigen::Matrix3d& base_R_tool)
|
||||
{
|
||||
if (emergency_stop_active_ && isZeroTwist(target_twist_input_) &&
|
||||
!linear_norm_planner_.isMoving() && !angular_norm_planner_.isMoving()) {
|
||||
restoreNominalConstraints();
|
||||
emergency_stop_active_ = false;
|
||||
}
|
||||
|
||||
if (input_frame_ == CartesianFrame::Base) {
|
||||
target_twist_base_ = target_twist_input_;
|
||||
} else {
|
||||
target_twist_base_ = transformTwistToolToBase(target_twist_input_, base_R_tool);
|
||||
}
|
||||
|
||||
// ==================== 线速度:方向锁定 + 标量 planner ====================
|
||||
const Eigen::Vector3d v_des = target_twist_base_.head<3>();
|
||||
const double v_des_norm = v_des.norm();
|
||||
const Eigen::Vector3d v_target_dir =
|
||||
chooseDirection(v_des,
|
||||
current_linear_dir_base_.norm() > EPSILON
|
||||
? current_linear_dir_base_
|
||||
: last_target_linear_dir_base_);
|
||||
|
||||
if (v_des_norm > EPSILON) {
|
||||
last_target_linear_dir_base_ = v_target_dir;
|
||||
}
|
||||
|
||||
const double v_cur_norm = linear_norm_planner_.getVelocity();
|
||||
const bool has_current_linear_dir = current_linear_dir_base_.norm() > EPSILON;
|
||||
if (!has_current_linear_dir) {
|
||||
if (v_des_norm > EPSILON) {
|
||||
current_linear_dir_base_ = v_target_dir;
|
||||
linear_norm_planner_.setTargetVelocity(v_des_norm);
|
||||
} else {
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
}
|
||||
} else if (v_des_norm <= EPSILON) {
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
} else {
|
||||
const double dir_dot =
|
||||
clamp(current_linear_dir_base_.dot(v_target_dir), -1.0, 1.0);
|
||||
const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD;
|
||||
const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD;
|
||||
const bool same_axis = axis_aligned || reverse_aligned;
|
||||
const bool must_switch_axis =
|
||||
!same_axis || dir_dot < linear_reverse_cos_threshold_;
|
||||
|
||||
if (continuous_linear_reversal_ && same_axis) {
|
||||
// Keep the axis fixed: the scalar profile carries the direction sign.
|
||||
// Crossing zero is an interior point, with continuous acceleration.
|
||||
linear_norm_planner_.setTargetVelocity(v_des.dot(current_linear_dir_base_));
|
||||
} else if (continuous_linear_reversal_ &&
|
||||
(std::abs(v_cur_norm) > EPSILON ||
|
||||
std::abs(linear_norm_planner_.getAcceleration()) > EPSILON ||
|
||||
linear_norm_planner_.hasActiveProfile())) {
|
||||
// A different axis may only be adopted after the old profile settles.
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
} else if (!continuous_linear_reversal_ && must_switch_axis &&
|
||||
v_cur_norm > linear_reverse_switch_speed_threshold_) {
|
||||
linear_norm_planner_.setTargetVelocity(0.0);
|
||||
} else {
|
||||
current_linear_dir_base_ = v_target_dir;
|
||||
linear_norm_planner_.setTargetVelocity(v_des_norm);
|
||||
}
|
||||
}
|
||||
|
||||
const double v_exec_norm = linear_norm_planner_.update(dt);
|
||||
twist_base_.head<3>() = current_linear_dir_base_ * v_exec_norm;
|
||||
|
||||
// ==================== 角速度:方向锁定 + 标量 planner ====================
|
||||
const Eigen::Vector3d w_des = target_twist_base_.tail<3>();
|
||||
const double w_des_norm = w_des.norm();
|
||||
const Eigen::Vector3d w_target_dir =
|
||||
chooseDirection(w_des,
|
||||
current_angular_dir_base_.norm() > EPSILON
|
||||
? current_angular_dir_base_
|
||||
: last_target_angular_dir_base_);
|
||||
|
||||
if (w_des_norm > EPSILON) {
|
||||
last_target_angular_dir_base_ = w_target_dir;
|
||||
}
|
||||
|
||||
const double w_cur_norm = angular_norm_planner_.getVelocity();
|
||||
const bool has_current_angular_dir = current_angular_dir_base_.norm() > EPSILON;
|
||||
if (!has_current_angular_dir) {
|
||||
if (w_des_norm > EPSILON) {
|
||||
current_angular_dir_base_ = w_target_dir;
|
||||
angular_norm_planner_.setTargetVelocity(w_des_norm);
|
||||
} else {
|
||||
angular_norm_planner_.setTargetVelocity(0.0);
|
||||
}
|
||||
} else if (w_des_norm <= EPSILON) {
|
||||
angular_norm_planner_.setTargetVelocity(0.0);
|
||||
} else {
|
||||
const double dir_dot =
|
||||
clamp(current_angular_dir_base_.dot(w_target_dir), -1.0, 1.0);
|
||||
const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD;
|
||||
const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD;
|
||||
const bool same_axis = axis_aligned || reverse_aligned;
|
||||
// 角速度与线速度一致:反向同轴也必须先减速到 0,再切方向。
|
||||
const bool must_switch_axis = !same_axis || reverse_aligned;
|
||||
|
||||
if (must_switch_axis && w_cur_norm > angular_switch_speed_threshold_) {
|
||||
angular_norm_planner_.setTargetVelocity(0.0);
|
||||
} else {
|
||||
current_angular_dir_base_ = w_target_dir;
|
||||
angular_norm_planner_.setTargetVelocity(w_des_norm);
|
||||
}
|
||||
}
|
||||
|
||||
const double w_exec_norm = angular_norm_planner_.update(dt);
|
||||
twist_base_.tail<3>() = current_angular_dir_base_ * w_exec_norm;
|
||||
|
||||
// ==================== 对最终 twist 做差分得到 acc / jerk ====================
|
||||
if (dt > EPSILON) {
|
||||
acceleration_base_ = (twist_base_ - prev_twist_base_) / dt;
|
||||
jerk_base_ = (acceleration_base_ - prev_acceleration_base_) / dt;
|
||||
} else {
|
||||
acceleration_base_.setZero();
|
||||
jerk_base_.setZero();
|
||||
}
|
||||
|
||||
prev_twist_base_ = twist_base_;
|
||||
prev_acceleration_base_ = acceleration_base_;
|
||||
|
||||
return twist_base_;
|
||||
}
|
||||
|
||||
bool CartesianTwistLimiter::isMoving() const
|
||||
{
|
||||
return linear_norm_planner_.isMoving() || angular_norm_planner_.isMoving();
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,118 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
using Twist = CartesianTwistLimiter::Twist;
|
||||
constexpr double dt = .001;
|
||||
Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; }
|
||||
struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; };
|
||||
Motion reverse(bool continuous, int approach_ticks) {
|
||||
CartesianTwistLimiter limiter;
|
||||
limiter.setLinearConstraints(.55, 5, 10);
|
||||
limiter.setContinuousLinearReversal(continuous);
|
||||
limiter.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero());
|
||||
limiter.setTargetTwist(y(.08), CartesianFrame::Base);
|
||||
for (int i = 0; i < approach_ticks; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
|
||||
limiter.setLinearConstraints(.55, 3, 10);
|
||||
limiter.setTargetTwist(y(-.08), CartesianFrame::Base);
|
||||
Motion result;
|
||||
double position = 0;
|
||||
for (int i = 1; i <= 1500; ++i) {
|
||||
const auto v = limiter.update(dt, Eigen::Matrix3d::Identity());
|
||||
position += v.y() * dt;
|
||||
result.peak = std::max(result.peak, position);
|
||||
if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt;
|
||||
if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt;
|
||||
if (continuous) {
|
||||
EXPECT_LE(limiter.getAccelerationBase().norm(), 3.0 + 1e-7);
|
||||
EXPECT_LE(limiter.getJerkBase().norm(), 10.0 + 1e-6);
|
||||
EXPECT_NEAR(v.x(), 0, 1e-12);
|
||||
EXPECT_NEAR(v.z(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
EXPECT_NEAR(limiter.getTwistBase().y(), -.08, 1e-9);
|
||||
return result;
|
||||
}
|
||||
TEST(CartesianTwistReversal, ContinuousReversalReducesTimeAndForwardTravel) {
|
||||
for (const int ticks : {0, 80, 120}) {
|
||||
SCOPED_TRACE(ticks);
|
||||
const auto legacy = reverse(false, ticks);
|
||||
const auto continuous = reverse(true, ticks);
|
||||
EXPECT_GT(continuous.reverse_time, 0);
|
||||
EXPECT_LT(continuous.reverse_time, legacy.reverse_time);
|
||||
EXPECT_LT(continuous.return_time, legacy.return_time);
|
||||
EXPECT_LT(continuous.peak, legacy.peak);
|
||||
}
|
||||
}
|
||||
TEST(CartesianTwistReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
|
||||
CartesianTwistLimiter limiter;
|
||||
limiter.setLinearConstraints(1, 1, 4);
|
||||
limiter.initialize(y(.02));
|
||||
limiter.setTargetTwist(y(-.02), CartesianFrame::Base);
|
||||
for (int i = 0; i < 100; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR(limiter.getTwistBase().y(), 0, 1e-12);
|
||||
EXPECT_TRUE(limiter.isMoving());
|
||||
EXPECT_LT(limiter.getAccelerationBase().y(), -.39);
|
||||
EXPECT_LT(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.0003);
|
||||
}
|
||||
TEST(CartesianTwistReversal, StopFromEitherDirectionSettlesWithoutReversing) {
|
||||
for (double v : {.08, -.08}) {
|
||||
CartesianTwistLimiter limiter;
|
||||
limiter.setLinearConstraints(1, 3, 10);
|
||||
limiter.initialize(y(v));
|
||||
limiter.stop();
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
EXPECT_GE(limiter.update(dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
|
||||
}
|
||||
EXPECT_FALSE(limiter.isMoving());
|
||||
EXPECT_NEAR(limiter.getTwistBase().norm(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
TEST(CartesianTwistReversal, FeedbackPreservesNegativeVelocityOnLockedAxis) {
|
||||
CartesianTwistLimiter limiter;
|
||||
limiter.setLinearConstraints(1, 3, 10);
|
||||
limiter.initialize(y(.08));
|
||||
limiter.setTargetTwist(y(-.08), CartesianFrame::Base);
|
||||
for (int i = 0; i < 400; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
limiter.synchronize(y(-.08), dt, true);
|
||||
EXPECT_NEAR(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.08, 1e-9);
|
||||
}
|
||||
}
|
||||
TEST(CartesianTwistReversal, NonCollinearChangeStopsBeforeSwitchingAxis) {
|
||||
CartesianTwistLimiter limiter;
|
||||
limiter.setLinearConstraints(1, 3, 10);
|
||||
limiter.initialize(y(.08));
|
||||
Twist x = Twist::Zero(); x.x() = .08;
|
||||
limiter.setTargetTwist(x, CartesianFrame::Base);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const auto v = limiter.update(dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_FALSE(v.x() > 1e-9 && std::abs(v.y()) > 1e-9);
|
||||
EXPECT_LE(limiter.getJerkBase().norm(), 10 + 1e-6);
|
||||
}
|
||||
EXPECT_NEAR(limiter.getTwistBase().x(), .08, 1e-9);
|
||||
}
|
||||
|
||||
TEST(CartesianTwistReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
|
||||
for (const int reverse_ticks : {150, 250, 500}) {
|
||||
SCOPED_TRACE(reverse_ticks);
|
||||
CartesianTwistLimiter reference;
|
||||
reference.setLinearConstraints(1, 3, 10);
|
||||
reference.initialize(y(.08));
|
||||
reference.setTargetTwist(y(-.08), CartesianFrame::Base);
|
||||
for (int i = 0; i < reverse_ticks; ++i) reference.update(dt, Eigen::Matrix3d::Identity());
|
||||
ASSERT_LT(reference.getTwistBase().y(), 0);
|
||||
auto streaming = reference;
|
||||
streaming.setContinuousLinearReversal(false);
|
||||
EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12);
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
const auto expected = reference.update(dt, Eigen::Matrix3d::Identity());
|
||||
const auto actual = streaming.update(dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR((actual - expected).norm(), 0, 1e-9);
|
||||
EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,90 +0,0 @@
|
||||
//
|
||||
// Created by lgv on 11/7/25.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Dense>
|
||||
#include <toppra/geometric_path/piecewise_poly_path.hpp>
|
||||
#include <toppra/parametrizer/const_accel.hpp>
|
||||
#include <toppra/parametrizer/spline.hpp>
|
||||
|
||||
namespace cmvr {
|
||||
// 统一轨迹接口
|
||||
struct ITrajectory {
|
||||
virtual ~ITrajectory() = default;
|
||||
virtual toppra::Bound timeInterval() const = 0;
|
||||
virtual Eigen::VectorXd q(double t) const = 0;
|
||||
virtual Eigen::VectorXd qd(double t) const = 0;
|
||||
virtual Eigen::VectorXd qdd(double t) const = 0;
|
||||
};
|
||||
using TrajPtr = std::shared_ptr<ITrajectory>;
|
||||
|
||||
struct TrajSample {
|
||||
double t{};
|
||||
Eigen::VectorXd q; // DoF x 1
|
||||
Eigen::VectorXd qd; // DoF x 1
|
||||
Eigen::VectorXd qdd; // DoF x 1
|
||||
};
|
||||
|
||||
// 三种几何路径
|
||||
enum class PathType { Linear,
|
||||
CubicHermite,
|
||||
Quintic,
|
||||
// 三次B样条
|
||||
Natural };
|
||||
class JointTrajectoryPlanner {
|
||||
public:
|
||||
|
||||
explicit JointTrajectoryPlanner(PathType p):path_type_(p){};
|
||||
JointTrajectoryPlanner()=default;
|
||||
virtual ~JointTrajectoryPlanner() = default;
|
||||
|
||||
virtual bool plan(const std::vector<double>& start_joints,
|
||||
const std::vector<double>& goal_joints,
|
||||
TrajPtr& traj) {
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual bool plan(const std::vector<std::vector<double>>& waypoints, TrajPtr& traj){
|
||||
return false;
|
||||
}
|
||||
|
||||
// 采样函数:从 ITrajectory 生成采样序列 dt(s)
|
||||
virtual std::vector<TrajSample> sampleTrajectory(const TrajPtr& traj, double dt) {
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
virtual bool writeTrajectoryCsv(const std::string& filename,const std::vector<TrajSample>& samples) {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 对称限:[-v_max, v_max]、[-a_max, a_max]
|
||||
virtual void setSymmetricLimits(const std::vector<double> &v_max,const std::vector<double> &a_max){
|
||||
v_max_ = v_max;
|
||||
a_max_ = a_max;
|
||||
}
|
||||
|
||||
// 可调网格密度(默认 150/300)
|
||||
virtual void setGridSizes(int N, int N_high)
|
||||
{
|
||||
N_grid_ = N;
|
||||
N_grid_high_ = N_high;
|
||||
}
|
||||
|
||||
// 切换几何路径类型
|
||||
virtual void setPathType(PathType p){path_type_ = p;}
|
||||
protected:
|
||||
PathType path_type_{PathType::Quintic};
|
||||
int N_grid_ = 150;
|
||||
int N_grid_high_ = 300;
|
||||
std::vector<double> v_max_, a_max_;
|
||||
|
||||
};
|
||||
}
|
||||
@ -1,209 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <Eigen/Dense>
|
||||
|
||||
#include "../../joint_trajectory_planner.h"
|
||||
#include <toppra/geometric_path/piecewise_poly_path.hpp>
|
||||
#include <toppra/parametrizer/const_accel.hpp>
|
||||
#include <toppra/parametrizer/spline.hpp>
|
||||
|
||||
namespace cmvr {
|
||||
// 适配器:ConstAccel
|
||||
class ConstAccelTraj : public ITrajectory {
|
||||
public:
|
||||
explicit ConstAccelTraj(std::shared_ptr<toppra::parametrizer::ConstAccel> p);
|
||||
|
||||
toppra::Bound timeInterval() const override;
|
||||
|
||||
Eigen::VectorXd q(double t) const override;
|
||||
|
||||
Eigen::VectorXd qd(double t) const override;
|
||||
|
||||
Eigen::VectorXd qdd(double t) const override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<toppra::parametrizer::ConstAccel> impl_;
|
||||
};
|
||||
|
||||
// 适配器:Spline
|
||||
class SplineTraj : public ITrajectory {
|
||||
public:
|
||||
SplineTraj(const std::shared_ptr<toppra::PiecewisePolyPath> &path,
|
||||
const toppra::Vector &grid,
|
||||
const toppra::Vector &vsq);
|
||||
|
||||
toppra::Bound timeInterval() const override;
|
||||
|
||||
Eigen::VectorXd q(double t) const override;
|
||||
|
||||
Eigen::VectorXd qd(double t) const override;
|
||||
|
||||
Eigen::VectorXd qdd(double t) const override;
|
||||
|
||||
private:
|
||||
toppra::parametrizer::Spline impl_;
|
||||
};
|
||||
|
||||
// 具体规划器:一次/三次/五次可切换;ConstAccel 校验失败自动回退 Spline
|
||||
class ToppraJointTrajectoryPlanner : public JointTrajectoryPlanner {
|
||||
public:
|
||||
explicit ToppraJointTrajectoryPlanner(PathType type = PathType::Quintic);
|
||||
|
||||
|
||||
// 统一入口:两点/多点皆可
|
||||
bool plan(const std::vector<std::vector<double> > &waypoints, TrajPtr &traj_out) override;
|
||||
|
||||
// 兼容旧 API(可选):转发为两点的统一入口
|
||||
bool plan(const std::vector<double> &start_joints,
|
||||
const std::vector<double> &goal_joints,
|
||||
TrajPtr &traj_out) override;
|
||||
|
||||
std::vector<TrajSample> sampleTrajectory(const TrajPtr &traj, double dt) override;
|
||||
|
||||
bool writeTrajectoryCsv(const std::string &filename, const std::vector<TrajSample> &samples) override;
|
||||
|
||||
private:
|
||||
// —— 几何路径统一分发 ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildPathUnified(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S);
|
||||
|
||||
// 二点专用
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildTwoPointPath(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildLinearTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildCubicHermiteTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildQuinticRestToRestTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildNaturalTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
|
||||
|
||||
// 多点
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildLinearMulti(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildCubicHermiteMulti(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildQuinticC2Multi(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S);
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
buildNaturalMulti(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S);
|
||||
|
||||
// —— 工具:限幅/参数/估计 ——
|
||||
bool ensureLimitsSized(std::size_t DoF);
|
||||
|
||||
static void sanitizeVsq(toppra::Vector &v);
|
||||
|
||||
|
||||
// Joint-space chord length keeps the parameterization independent of
|
||||
// how densely the same geometric path is sampled.
|
||||
static std::vector<toppra::value_type>
|
||||
makeSChordLength(const std::vector<Eigen::VectorXd> &q) {
|
||||
const size_t M = q.size();
|
||||
std::vector<toppra::value_type> S(M, 0.0);
|
||||
for (size_t i = 1; i < M; ++i) {
|
||||
S[i] = S[i - 1] + (q[i] - q[i - 1]).norm();
|
||||
}
|
||||
return S;
|
||||
}
|
||||
|
||||
// Catmull–Rom(centripetal)估计结点几何速度 v(端点=0)
|
||||
static std::vector<Eigen::VectorXd>
|
||||
estimateVelsCatmull(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S) {
|
||||
const size_t M = q.size();
|
||||
const int DoF = static_cast<int>(q[0].size());
|
||||
std::vector<Eigen::VectorXd> v(M, Eigen::VectorXd::Zero(DoF));
|
||||
if (M <= 2) return v;
|
||||
for (size_t i = 1; i + 1 < M; ++i) {
|
||||
double ds0 = std::max<double>(S[i] - S[i - 1], 1e-12);
|
||||
double ds1 = std::max<double>(S[i + 1] - S[i], 1e-12);
|
||||
v[i] = ((q[i + 1] - q[i]) / ds1 * ds0 + (q[i] - q[i - 1]) / ds0 * ds1) / (ds0 + ds1);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// 对内点几何速度限幅,抑制过冲(k∈[0.5,1.0])
|
||||
static void clampNodeVels(std::vector<Eigen::VectorXd> &v,
|
||||
const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S,
|
||||
double k = 1.0) {
|
||||
const size_t M = q.size();
|
||||
if (M <= 2) return;
|
||||
for (size_t i = 1; i + 1 < M; ++i) {
|
||||
const double ds0 = std::max<double>(S[i] - S[i - 1], 1e-12);
|
||||
const double ds1 = std::max<double>(S[i + 1] - S[i], 1e-12);
|
||||
const double slope0 = (q[i] - q[i - 1]).norm() / ds0;
|
||||
const double slope1 = (q[i + 1] - q[i]).norm() / ds1;
|
||||
const double vmax = k * std::min(slope0, slope1);
|
||||
double n = v[i].norm();
|
||||
if (n > vmax) v[i] *= (vmax / n);
|
||||
}
|
||||
}
|
||||
|
||||
// 估计结点几何加速度 a(端点=0;中点二阶差分,按 s 尺度)
|
||||
static std::vector<Eigen::VectorXd>
|
||||
estimateAccelsSecondDiff(const std::vector<Eigen::VectorXd> &q,
|
||||
const std::vector<toppra::value_type> &S) {
|
||||
const size_t M = q.size();
|
||||
const int DoF = static_cast<int>(q[0].size());
|
||||
std::vector<Eigen::VectorXd> a(M, Eigen::VectorXd::Zero(DoF));
|
||||
if (M <= 2) return a;
|
||||
for (size_t i = 1; i + 1 < M; ++i) {
|
||||
double h0 = std::max<double>(S[i] - S[i - 1], 1e-12); // 左间距
|
||||
double h1 = std::max<double>(S[i + 1] - S[i], 1e-12); // 右间距
|
||||
double denom = 0.5 * (h0 + h1); // 局部尺度
|
||||
// 非均匀中心二阶差分(更精确):
|
||||
// a ≈ 2 * [ (q_{i+1}-q_i)/h1 - (q_i - q_{i-1})/h0 ] / (h0 + h1)
|
||||
a[i] = 2.0 * ((q[i + 1] - q[i]) / h1 - (q[i] - q[i - 1]) / h0) / (h0 + h1);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
|
||||
// τ→s 变元:把局部 Quintic(τ) 的系数 c_tau[0..5](τ^0..τ^5)
|
||||
// 变成全局 s 的系数 alpha[0..5](s^0..s^5),其中 τ = (s - S_k) / ds
|
||||
static inline void localQuinticToGlobalCoeffs(
|
||||
const std::array<Eigen::VectorXd, 6> &c_tau, // c0..c5(DoF维向量)
|
||||
double Sk, double ds,
|
||||
std::array<Eigen::VectorXd, 6> &alpha // α0..α5(DoF维向量)
|
||||
) {
|
||||
static const double C[6][6] = {
|
||||
// binomial(n,m)
|
||||
{1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 0, 0, 0, 0},
|
||||
{1, 2, 1, 0, 0, 0},
|
||||
{1, 3, 3, 1, 0, 0},
|
||||
{1, 4, 6, 4, 1, 0},
|
||||
{1, 5, 10, 10, 5, 1}
|
||||
};
|
||||
const double eps = 1e-12;
|
||||
ds = std::max(ds, eps);
|
||||
|
||||
for (int m = 0; m <= 5; ++m) alpha[m].setZero(c_tau[0].size());
|
||||
|
||||
// α_m = Σ_{n=m..5} c_n * C(n,m) * (-S_k)^{n-m} / ds^{n}
|
||||
for (int n = 0; n <= 5; ++n) {
|
||||
double invdsn = std::pow(ds, -n);
|
||||
for (int m = 0; m <= n; ++m) {
|
||||
double factor = C[n][m] * std::pow(-Sk, n - m) * invdsn;
|
||||
alpha[m].noalias() += factor * c_tau[n];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace cmvr
|
||||
@ -1,527 +0,0 @@
|
||||
#include <toppra/algorithm/toppra.hpp>
|
||||
#include <toppra/constraint/linear_joint_velocity.hpp>
|
||||
#include <toppra/constraint/linear_joint_acceleration.hpp>
|
||||
#include <toppra/solver/seidel.hpp>
|
||||
#include <toppra/toppra.hpp>
|
||||
#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
class TimeScaledTrajectory final : public ITrajectory {
|
||||
public:
|
||||
TimeScaledTrajectory(TrajPtr source, const double scale)
|
||||
: source_(std::move(source)), scale_(scale), source_interval_(source_->timeInterval())
|
||||
{
|
||||
}
|
||||
|
||||
toppra::Bound timeInterval() const override
|
||||
{
|
||||
toppra::Bound interval;
|
||||
interval << source_interval_[0],
|
||||
source_interval_[0] +
|
||||
(source_interval_[1] - source_interval_[0]) * scale_;
|
||||
return interval;
|
||||
}
|
||||
|
||||
Eigen::VectorXd q(const double t) const override
|
||||
{
|
||||
return source_->q(sourceTime_(t));
|
||||
}
|
||||
|
||||
Eigen::VectorXd qd(const double t) const override
|
||||
{
|
||||
return source_->qd(sourceTime_(t)) / scale_;
|
||||
}
|
||||
|
||||
Eigen::VectorXd qdd(const double t) const override
|
||||
{
|
||||
return source_->qdd(sourceTime_(t)) / (scale_ * scale_);
|
||||
}
|
||||
|
||||
private:
|
||||
double sourceTime_(const double output_time) const
|
||||
{
|
||||
return std::clamp(
|
||||
source_interval_[0] +
|
||||
(output_time - source_interval_[0]) / scale_,
|
||||
source_interval_[0],
|
||||
source_interval_[1]);
|
||||
}
|
||||
|
||||
TrajPtr source_;
|
||||
double scale_{1.0};
|
||||
toppra::Bound source_interval_;
|
||||
};
|
||||
|
||||
bool enforceSampledLimits(const TrajPtr& source,
|
||||
const std::vector<double>& velocity_limits,
|
||||
const std::vector<double>& acceleration_limits,
|
||||
const std::size_t waypoint_count,
|
||||
TrajPtr& output)
|
||||
{
|
||||
if (!source || velocity_limits.empty() ||
|
||||
velocity_limits.size() != acceleration_limits.size()) {
|
||||
return false;
|
||||
}
|
||||
const auto interval = source->timeInterval();
|
||||
const double duration = interval[1] - interval[0];
|
||||
if (!std::isfinite(duration) || duration <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::size_t time_samples = static_cast<std::size_t>(
|
||||
std::ceil(duration / 0.001)) + 1;
|
||||
const std::size_t path_samples = waypoint_count * 20;
|
||||
const std::size_t sample_count = std::clamp<std::size_t>(
|
||||
std::max({std::size_t{1000}, time_samples, path_samples}),
|
||||
std::size_t{1000},
|
||||
std::size_t{200000});
|
||||
|
||||
double required_scale = 1.0;
|
||||
for (std::size_t sample = 0; sample < sample_count; ++sample) {
|
||||
const double ratio = static_cast<double>(sample) /
|
||||
static_cast<double>(sample_count - 1);
|
||||
const double time = interval[0] + duration * ratio;
|
||||
const Eigen::VectorXd velocity = source->qd(time);
|
||||
const Eigen::VectorXd acceleration = source->qdd(time);
|
||||
if (!velocity.allFinite() || !acceleration.allFinite() ||
|
||||
velocity.size() != static_cast<Eigen::Index>(velocity_limits.size()) ||
|
||||
acceleration.size() !=
|
||||
static_cast<Eigen::Index>(acceleration_limits.size())) {
|
||||
return false;
|
||||
}
|
||||
for (Eigen::Index joint = 0; joint < velocity.size(); ++joint) {
|
||||
const std::size_t index = static_cast<std::size_t>(joint);
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::abs(velocity[joint]) / velocity_limits[index]);
|
||||
required_scale = std::max(
|
||||
required_scale,
|
||||
std::sqrt(std::abs(acceleration[joint]) /
|
||||
acceleration_limits[index]));
|
||||
}
|
||||
}
|
||||
|
||||
constexpr double kNumericalMargin = 1.001;
|
||||
output = std::make_shared<TimeScaledTrajectory>(
|
||||
source, required_scale * kNumericalMargin);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ===== ConstAccelTraj =====
|
||||
ConstAccelTraj::ConstAccelTraj(std::shared_ptr<toppra::parametrizer::ConstAccel> p)
|
||||
: impl_(std::move(p)) {
|
||||
}
|
||||
|
||||
toppra::Bound ConstAccelTraj::timeInterval() const { return impl_->pathInterval(); }
|
||||
Eigen::VectorXd ConstAccelTraj::q(double t) const { return impl_->eval_single(t, 0); }
|
||||
Eigen::VectorXd ConstAccelTraj::qd(double t) const { return impl_->eval_single(t, 1); }
|
||||
Eigen::VectorXd ConstAccelTraj::qdd(double t) const { return impl_->eval_single(t, 2); }
|
||||
|
||||
// ===== SplineTraj =====
|
||||
SplineTraj::SplineTraj(const std::shared_ptr<toppra::PiecewisePolyPath> &path,
|
||||
const toppra::Vector &grid,
|
||||
const toppra::Vector &vsq)
|
||||
: impl_(path, grid, vsq) {
|
||||
}
|
||||
|
||||
toppra::Bound SplineTraj::timeInterval() const { return impl_.pathInterval(); }
|
||||
Eigen::VectorXd SplineTraj::q(double t) const { return impl_.eval_single(t, 0); }
|
||||
Eigen::VectorXd SplineTraj::qd(double t) const { return impl_.eval_single(t, 1); }
|
||||
Eigen::VectorXd SplineTraj::qdd(double t) const { return impl_.eval_single(t, 2); }
|
||||
|
||||
// ===== ToppraJointTrajectoryPlanner =====
|
||||
ToppraJointTrajectoryPlanner::ToppraJointTrajectoryPlanner(PathType type) :JointTrajectoryPlanner(type) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool ToppraJointTrajectoryPlanner::ensureLimitsSized(std::size_t DoF) {
|
||||
if (v_max_.size() != DoF) v_max_.assign(DoF, 1.5);
|
||||
if (a_max_.size() != DoF) a_max_.assign(DoF, 3.0);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ToppraJointTrajectoryPlanner::sanitizeVsq(toppra::Vector &v) {
|
||||
for (int i = 0; i < v.size(); ++i) if (v[i] < 0 && v[i] > -1e-10) v[i] = 0;
|
||||
if (v.size() > 0) {
|
||||
v[0] = 0;
|
||||
v[v.size() - 1] = 0;
|
||||
}
|
||||
}
|
||||
// ===== 统一入口:两点/多点 =====
|
||||
bool ToppraJointTrajectoryPlanner::plan(const std::vector<std::vector<double>>& waypoints,
|
||||
TrajPtr& traj_out) {
|
||||
traj_out.reset();
|
||||
if (waypoints.size() < 2) return false;
|
||||
const size_t DoF = waypoints.front().size();
|
||||
if (DoF == 0) return false;
|
||||
for (const auto& w : waypoints) {
|
||||
if (w.size() != DoF) return false;
|
||||
for (const double value : w) {
|
||||
if (!std::isfinite(value)) return false;
|
||||
}
|
||||
}
|
||||
if (!ensureLimitsSized(DoF)) return false;
|
||||
for (size_t joint = 0; joint < DoF; ++joint) {
|
||||
if (!std::isfinite(v_max_[joint]) || v_max_[joint] <= 0.0 ||
|
||||
!std::isfinite(a_max_[joint]) || a_max_[joint] <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<Eigen::VectorXd> q;
|
||||
q.reserve(waypoints.size());
|
||||
constexpr double kDuplicateDistance = 1e-10;
|
||||
for (const auto& waypoint : waypoints) {
|
||||
Eigen::VectorXd value = Eigen::Map<const Eigen::VectorXd>(
|
||||
waypoint.data(), static_cast<Eigen::Index>(DoF));
|
||||
if (q.empty() || (value - q.back()).norm() > kDuplicateDistance) {
|
||||
q.push_back(std::move(value));
|
||||
}
|
||||
}
|
||||
if (q.size() < 2) return false;
|
||||
const size_t M = q.size();
|
||||
|
||||
const std::vector<toppra::value_type> S = M == 2
|
||||
? std::vector<toppra::value_type>{0.0, 1.0}
|
||||
: makeSChordLength(q);
|
||||
|
||||
// 几何路径
|
||||
auto path = buildPathUnified(q, S);
|
||||
if (!path) return false;
|
||||
|
||||
// 约束
|
||||
Eigen::VectorXd vmax(DoF), amax(DoF);
|
||||
for (size_t i=0;i<DoF;++i) { vmax[i]=v_max_[i]; amax[i]=a_max_[i]; }
|
||||
auto vel = std::make_shared<toppra::constraint::LinearJointVelocity>(-vmax, vmax);
|
||||
auto acc = std::make_shared<toppra::constraint::LinearJointAcceleration>(-amax, amax);
|
||||
vel->discretizationType(toppra::DiscretizationType::Collocation);
|
||||
acc->discretizationType(toppra::DiscretizationType::Interpolation);
|
||||
toppra::LinearConstraintPtrs constraints{vel, acc};
|
||||
|
||||
// TOPPRA
|
||||
toppra::algorithm::TOPPRA algo{constraints, path};
|
||||
auto solve_once = [&](const int requested_intervals)->bool{
|
||||
const int segment_count = static_cast<int>(M - 1);
|
||||
const int subdivisions = std::max(
|
||||
1, (requested_intervals + segment_count - 1) / segment_count);
|
||||
toppra::Vector grid(segment_count * subdivisions + 1);
|
||||
Eigen::Index index = 0;
|
||||
for (int segment = 0; segment < segment_count; ++segment) {
|
||||
const double start = S[static_cast<size_t>(segment)];
|
||||
const double length = S[static_cast<size_t>(segment + 1)] - start;
|
||||
for (int subdivision = 0; subdivision < subdivisions; ++subdivision) {
|
||||
grid[index++] = start + length *
|
||||
static_cast<double>(subdivision) /
|
||||
static_cast<double>(subdivisions);
|
||||
}
|
||||
}
|
||||
grid[index] = S.back();
|
||||
algo.setGridpoints(grid);
|
||||
algo.solver(std::make_shared<toppra::solver::Seidel>());
|
||||
return algo.computePathParametrization(0.0, 0.0) == toppra::ReturnCode::OK;
|
||||
};
|
||||
if (!solve_once(N_grid_)) {
|
||||
if (!solve_once(N_grid_high_)) return false;
|
||||
}
|
||||
|
||||
const auto data = algo.getParameterizationData();
|
||||
toppra::Vector grid = data.gridpoints;
|
||||
toppra::Vector vsq = data.parametrization;
|
||||
|
||||
TrajPtr candidate;
|
||||
auto ca = std::make_shared<toppra::parametrizer::ConstAccel>(path, grid, vsq);
|
||||
if (ca->validate()) {
|
||||
candidate = std::make_shared<ConstAccelTraj>(std::move(ca));
|
||||
} else {
|
||||
sanitizeVsq(vsq);
|
||||
try {
|
||||
candidate = std::make_shared<SplineTraj>(path, grid, vsq);
|
||||
(void) candidate->timeInterval();
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return enforceSampledLimits(candidate, v_max_, a_max_, M, traj_out);
|
||||
}
|
||||
|
||||
|
||||
bool ToppraJointTrajectoryPlanner::plan(const std::vector<double>& start_joints,
|
||||
const std::vector<double>& goal_joints,
|
||||
TrajPtr& traj_out) {
|
||||
if (start_joints.empty() || start_joints.size()!=goal_joints.size()) return false;
|
||||
std::vector<std::vector<double>> wpts{start_joints, goal_joints};
|
||||
return plan(wpts, traj_out);
|
||||
}
|
||||
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildPathUnified(const std::vector<Eigen::VectorXd>& q,
|
||||
const std::vector<toppra::value_type>& S) {
|
||||
const size_t M = q.size();
|
||||
if (M == 2) return buildTwoPointPath(q[0], q[1]);
|
||||
switch (path_type_) {
|
||||
case PathType::Linear: return buildLinearMulti(q, S);
|
||||
case PathType::CubicHermite: return buildCubicHermiteMulti(q, S);
|
||||
case PathType::Natural: return buildNaturalMulti(q, S);
|
||||
case PathType::Quintic:
|
||||
default: return buildQuinticC2Multi(q, S);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildTwoPointPath(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
|
||||
switch (path_type_) {
|
||||
case PathType::Linear: return buildLinearTwo(q0, q1);
|
||||
case PathType::CubicHermite: return buildCubicHermiteTwo(q0, q1);
|
||||
case PathType::Natural: return buildNaturalTwo(q0, q1);
|
||||
case PathType::Quintic:
|
||||
default: return buildQuinticRestToRestTwo(q0, q1);
|
||||
}
|
||||
}
|
||||
|
||||
// 二点:Linear ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildLinearTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
|
||||
const size_t DoF = static_cast<size_t>(q0.size());
|
||||
toppra::Matrix seg(2, DoF);
|
||||
seg.row(0) = (q1 - q0).transpose();
|
||||
seg.row(1) = q0.transpose();
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(
|
||||
toppra::Matrices{seg}, std::vector<double>{0.0, 1.0});
|
||||
}
|
||||
|
||||
// 二点:Cubic Hermite(端点速度 0) ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildCubicHermiteTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
|
||||
toppra::Vectors pos{q0, q1};
|
||||
toppra::Vectors vel{Eigen::VectorXd::Zero(q0.size()),
|
||||
Eigen::VectorXd::Zero(q1.size())};
|
||||
std::vector<toppra::value_type> s{0.0, 1.0};
|
||||
auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, s);
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(herm);
|
||||
}
|
||||
|
||||
// 二点:Quintic rest-to-rest ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildQuinticRestToRestTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
|
||||
const size_t DoF = static_cast<size_t>(q0.size());
|
||||
const Eigen::VectorXd dq = q1 - q0;
|
||||
toppra::Matrix seg(6, DoF); // x^5..x^0
|
||||
seg.row(0) = ( 6.0 * dq).transpose();
|
||||
seg.row(1) = (-15.0 * dq).transpose();
|
||||
seg.row(2) = (10.0 * dq).transpose();
|
||||
seg.row(3).setZero(); seg.row(4).setZero();
|
||||
seg.row(5) = q0.transpose();
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(
|
||||
toppra::Matrices{seg}, std::vector<double>{0.0, 1.0});
|
||||
}
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildNaturalTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
|
||||
using PWP = toppra::PiecewisePolyPath;
|
||||
|
||||
// positions(两点)
|
||||
toppra::Vectors pos{ q0, q1 };
|
||||
|
||||
// 自变量S:两点用等距最简单
|
||||
toppra::Vector S(2);
|
||||
S[0] = 0.0; S[1] = 1.0;
|
||||
|
||||
|
||||
toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"),
|
||||
toppra::BoundaryCond("clamped") };
|
||||
auto path = PWP::CubicSpline(pos, S, bcA);
|
||||
return std::make_shared<PWP>(path);
|
||||
|
||||
// 手动指定二阶导为 0
|
||||
// const int DoF = static_cast<int>(q0.size());
|
||||
// toppra::BoundaryCondFull bcB = {
|
||||
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)),
|
||||
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF))
|
||||
// };
|
||||
// auto path2 = PWP::CubicSpline(pos, S, bcB);
|
||||
// return std::make_shared<PWP>(path2);
|
||||
}
|
||||
|
||||
|
||||
// —— 多点:Linear ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildLinearMulti(const std::vector<Eigen::VectorXd>& q,
|
||||
const std::vector<toppra::value_type>& S) {
|
||||
const size_t M = q.size(), DoF = q[0].size();
|
||||
toppra::Matrices segs; segs.reserve(M-1);
|
||||
for (size_t k=0;k+1<M;++k) {
|
||||
double ds = std::max<double>(S[k+1]-S[k], 1e-12);
|
||||
toppra::Matrix seg(2, DoF);
|
||||
Eigen::RowVectorXd A1 = ((q[k+1]-q[k])/ds).transpose();
|
||||
Eigen::RowVectorXd A0 = q[k].transpose();
|
||||
seg.row(0)=A1; seg.row(1)=A0;
|
||||
segs.emplace_back(std::move(seg));
|
||||
}
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(segs, std::vector<double>(S.begin(), S.end()));
|
||||
}
|
||||
|
||||
// —— 多点:Cubic Hermite ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildCubicHermiteMulti(const std::vector<Eigen::VectorXd>& q,
|
||||
const std::vector<toppra::value_type>& S) {
|
||||
auto v = estimateVelsCatmull(q, S);
|
||||
clampNodeVels(v, q, S, /*k=*/1.0);
|
||||
toppra::Vectors pos(q.begin(), q.end());
|
||||
toppra::Vectors vel(v.begin(), v.end());
|
||||
auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, S);
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(herm);
|
||||
}
|
||||
|
||||
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildNaturalMulti(const std::vector<Eigen::VectorXd>& q,
|
||||
const std::vector<toppra::value_type>& S) {
|
||||
using PWP = toppra::PiecewisePolyPath;
|
||||
|
||||
const size_t M = q.size();
|
||||
if (M < 2 || M != S.size()) return nullptr;
|
||||
|
||||
// positions
|
||||
toppra::Vectors pos(q.begin(), q.end());
|
||||
|
||||
// times(全局自变量,需严格递增)
|
||||
toppra::Vector times(static_cast<int>(M));
|
||||
for (size_t i = 0; i < M; ++i) times[static_cast<int>(i)] = S[i];
|
||||
|
||||
//Natural
|
||||
toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"),
|
||||
toppra::BoundaryCond("clamped") };
|
||||
auto path = PWP::CubicSpline(pos, times, bcA);
|
||||
return std::make_shared<PWP>(path);
|
||||
|
||||
// 手动指定二阶导为 0 ——
|
||||
// const int DoF = static_cast<int>(q[0].size());
|
||||
// toppra::BoundaryCondFull bcB = {
|
||||
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)),
|
||||
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF))
|
||||
// };
|
||||
// auto path2 = PWP::CubicSpline(pos, times, bcB);
|
||||
// return std::make_shared<PWP>(path2);
|
||||
}
|
||||
|
||||
// —— 多点:Quintic C² ——
|
||||
std::shared_ptr<toppra::PiecewisePolyPath>
|
||||
ToppraJointTrajectoryPlanner::buildQuinticC2Multi(const std::vector<Eigen::VectorXd>& q,
|
||||
const std::vector<toppra::value_type>& S) {
|
||||
const size_t M = q.size(), DoF = q[0].size();
|
||||
auto v = estimateVelsCatmull(q, S);
|
||||
clampNodeVels(v, q, S, /*k=*/1.0);
|
||||
auto a = estimateAccelsSecondDiff(q, S);
|
||||
|
||||
toppra::Matrices segs; segs.reserve(M-1);
|
||||
for (size_t k=0;k+1<M;++k) {
|
||||
const double ds = std::max<double>(S[k+1]-S[k], 1e-12);
|
||||
const Eigen::VectorXd& q0=q[k]; const Eigen::VectorXd& q1=q[k+1];
|
||||
const Eigen::VectorXd& v0=v[k]; const Eigen::VectorXd& v1=v[k+1];
|
||||
const Eigen::VectorXd& a0=a[k]; const Eigen::VectorXd& a1=a[k+1];
|
||||
const Eigen::VectorXd dq = q1-q0;
|
||||
|
||||
Eigen::VectorXd A0 = q0;
|
||||
Eigen::VectorXd A1 = v0 * ds;
|
||||
Eigen::VectorXd A2 = a0 * (ds*ds) / 2.0;
|
||||
Eigen::VectorXd C3 = ( 10.0*dq - (6.0*A1 + 1.5*(a0*ds*ds)) - (4.0*(v1*ds) - 0.5*(a1*ds*ds)) );
|
||||
Eigen::VectorXd C4 = (-15.0*dq + (8.0*A1 + 1.5*(a0*ds*ds)) + (7.0*(v1*ds) - 1.0*(a1*ds*ds)) );
|
||||
Eigen::VectorXd C5 = ( 6.0*dq - (3.0*A1 + 0.5*(a0*ds*ds)) - (3.0*(v1*ds) - 0.5*(a1*ds*ds)) );
|
||||
|
||||
toppra::Matrix seg(6, DoF);
|
||||
seg.row(0)=(C5 / std::pow(ds, 5)).transpose();
|
||||
seg.row(1)=(C4 / std::pow(ds, 4)).transpose();
|
||||
seg.row(2)=(C3 / std::pow(ds, 3)).transpose();
|
||||
seg.row(3)=(a0 / 2.0).transpose();
|
||||
seg.row(4)=v0.transpose();
|
||||
seg.row(5)=A0.transpose();
|
||||
segs.emplace_back(std::move(seg));
|
||||
}
|
||||
return std::make_shared<toppra::PiecewisePolyPath>(segs, std::vector<double>(S.begin(), S.end()));
|
||||
}
|
||||
|
||||
std::vector<TrajSample> ToppraJointTrajectoryPlanner::sampleTrajectory(const TrajPtr &traj, double dt) {
|
||||
std::vector<TrajSample> out;
|
||||
if (!traj) return out;
|
||||
|
||||
auto I = traj->timeInterval();
|
||||
const double t0 = I[0];
|
||||
const double t1 = I[1];
|
||||
if (!(t1 > t0)) return out;
|
||||
|
||||
// 2) 生成时间序列(含端点,考虑浮点误差)
|
||||
constexpr double EPS = 1e-12;
|
||||
std::vector<double> ts;
|
||||
ts.reserve(static_cast<size_t>(std::max(2.0, std::ceil((t1 - t0) / dt) + 1.0)));
|
||||
|
||||
// 起点
|
||||
ts.push_back(t0);
|
||||
|
||||
// 中间等间隔点
|
||||
for (double t = t0 + dt; t <= t1 - EPS; t += dt) {
|
||||
// 防守式:避免因累积误差越过 t1
|
||||
ts.push_back((t > t1) ? t1 : t);
|
||||
}
|
||||
|
||||
// 终点(若未加入)
|
||||
if (ts.empty() || std::fabs(ts.back() - t1) > EPS) {
|
||||
ts.push_back(t1);
|
||||
} else {
|
||||
// 若最后一个点因误差“很接近 t1”,直接覆盖为 t1
|
||||
ts.back() = t1;
|
||||
}
|
||||
|
||||
// 3) 采样
|
||||
out.reserve(ts.size());
|
||||
for (double t: ts) {
|
||||
TrajSample s;
|
||||
s.t = t;
|
||||
s.q = traj->q(t);
|
||||
s.qd = traj->qd(t);
|
||||
s.qdd = traj->qdd(t);
|
||||
out.emplace_back(std::move(s));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
bool ToppraJointTrajectoryPlanner::writeTrajectoryCsv(const std::string &filename, const std::vector<TrajSample> &samples) {
|
||||
if (samples.empty()) return false;
|
||||
|
||||
const int dof = static_cast<int>(samples.front().q.size());
|
||||
std::ofstream ofs(filename);
|
||||
if (!ofs) return false;
|
||||
|
||||
ofs.setf(std::ios::fixed);
|
||||
ofs << std::setprecision(10);
|
||||
|
||||
// 表头
|
||||
ofs << "t";
|
||||
for (int j=1;j<=dof;++j) ofs << ",q" << j;
|
||||
for (int j=1;j<=dof;++j) ofs << ",qd" << j;
|
||||
for (int j=1;j<=dof;++j) ofs << ",qdd" << j;
|
||||
ofs << "\n";
|
||||
|
||||
// 内容
|
||||
for (const auto& s : samples) {
|
||||
ofs << s.t;
|
||||
for (int j=0;j<dof;++j) ofs << "," << s.q[j];
|
||||
for (int j=0;j<dof;++j) ofs << "," << s.qd[j];
|
||||
for (int j=0;j<dof;++j) ofs << "," << s.qdd[j];
|
||||
ofs << "\n";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace cmvr
|
||||
@ -1,228 +0,0 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t kDof = 7;
|
||||
constexpr double kVelocityLimit = 0.15;
|
||||
constexpr double kAccelerationLimit = 0.3;
|
||||
constexpr double kSamplePeriodS = 0.002;
|
||||
|
||||
std::vector<std::vector<double>> makeSmoothWaypoints(const std::size_t count)
|
||||
{
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
std::vector<std::vector<double>> waypoints;
|
||||
waypoints.reserve(count);
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
const double s = static_cast<double>(i) /
|
||||
static_cast<double>(count - 1);
|
||||
std::vector<double> q(kDof, 0.0);
|
||||
q[0] = 0.40 * s + 0.03 * std::sin(2.0 * kPi * s);
|
||||
q[1] = -0.25 * s + 0.04 * std::sin(kPi * s);
|
||||
q[2] = 0.20 * s * s;
|
||||
q[3] = 0.30 * std::sin(0.5 * kPi * s);
|
||||
q[4] = -0.12 * s + 0.02 * std::sin(3.0 * kPi * s);
|
||||
q[5] = 0.15 * s;
|
||||
q[6] = -0.08 * std::sin(kPi * s);
|
||||
waypoints.push_back(std::move(q));
|
||||
}
|
||||
return waypoints;
|
||||
}
|
||||
|
||||
double maxAbs(const Eigen::VectorXd& value)
|
||||
{
|
||||
double result = 0.0;
|
||||
for (Eigen::Index i = 0; i < value.size(); ++i) {
|
||||
result = std::max(result, std::abs(value[i]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
double positionError(const Eigen::VectorXd& actual,
|
||||
const std::vector<double>& expected)
|
||||
{
|
||||
if (actual.size() != static_cast<Eigen::Index>(expected.size())) {
|
||||
return std::numeric_limits<double>::infinity();
|
||||
}
|
||||
double squared_error = 0.0;
|
||||
for (Eigen::Index i = 0; i < actual.size(); ++i) {
|
||||
const double error = actual[i] - expected[static_cast<std::size_t>(i)];
|
||||
squared_error += error * error;
|
||||
}
|
||||
return std::sqrt(squared_error);
|
||||
}
|
||||
|
||||
struct PlanMetrics {
|
||||
bool success{false};
|
||||
double planning_ms{0.0};
|
||||
double duration_s{0.0};
|
||||
double max_velocity{0.0};
|
||||
double max_acceleration{0.0};
|
||||
double max_waypoint_error{0.0};
|
||||
double start_error{0.0};
|
||||
double end_error{0.0};
|
||||
std::size_t sample_count{0};
|
||||
};
|
||||
|
||||
PlanMetrics planAndMeasure(const std::vector<std::vector<double>>& waypoints,
|
||||
const PathType path_type = PathType::Linear)
|
||||
{
|
||||
PlanMetrics metrics;
|
||||
ToppraJointTrajectoryPlanner planner(path_type);
|
||||
planner.setSymmetricLimits(
|
||||
std::vector<double>(kDof, kVelocityLimit),
|
||||
std::vector<double>(kDof, kAccelerationLimit));
|
||||
planner.setGridSizes(150, 300);
|
||||
|
||||
TrajPtr trajectory;
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
metrics.success = planner.plan(waypoints, trajectory);
|
||||
metrics.planning_ms = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
if (!metrics.success || !trajectory) {
|
||||
return metrics;
|
||||
}
|
||||
|
||||
const auto interval = trajectory->timeInterval();
|
||||
metrics.duration_s = interval[1] - interval[0];
|
||||
const auto samples = planner.sampleTrajectory(trajectory, kSamplePeriodS);
|
||||
metrics.sample_count = samples.size();
|
||||
if (samples.empty()) {
|
||||
metrics.success = false;
|
||||
return metrics;
|
||||
}
|
||||
metrics.start_error = positionError(samples.front().q, waypoints.front());
|
||||
metrics.end_error = positionError(samples.back().q, waypoints.back());
|
||||
|
||||
for (const auto& sample : samples) {
|
||||
if (!std::isfinite(sample.t) || !sample.q.allFinite() ||
|
||||
!sample.qd.allFinite() || !sample.qdd.allFinite()) {
|
||||
metrics.success = false;
|
||||
return metrics;
|
||||
}
|
||||
metrics.max_velocity = std::max(metrics.max_velocity, maxAbs(sample.qd));
|
||||
metrics.max_acceleration = std::max(
|
||||
metrics.max_acceleration, maxAbs(sample.qdd));
|
||||
}
|
||||
|
||||
std::size_t sample_index = 0;
|
||||
for (const auto& waypoint : waypoints) {
|
||||
while (sample_index + 1 < samples.size() &&
|
||||
positionError(samples[sample_index + 1].q, waypoint) <=
|
||||
positionError(samples[sample_index].q, waypoint)) {
|
||||
++sample_index;
|
||||
}
|
||||
metrics.max_waypoint_error = std::max(
|
||||
metrics.max_waypoint_error,
|
||||
positionError(samples[sample_index].q, waypoint));
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
|
||||
const char* pathTypeName(const PathType path_type)
|
||||
{
|
||||
switch (path_type) {
|
||||
case PathType::Linear: return "Linear";
|
||||
case PathType::CubicHermite: return "CubicHermite";
|
||||
case PathType::Quintic: return "Quintic";
|
||||
case PathType::Natural: return "Natural";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
void printMetrics(const std::size_t waypoint_count, const PlanMetrics& metrics)
|
||||
{
|
||||
std::cout << "[ToppraMultiWaypointTest] waypoints=" << waypoint_count
|
||||
<< ", success=" << metrics.success
|
||||
<< ", planning_ms=" << metrics.planning_ms
|
||||
<< ", duration_s=" << metrics.duration_s
|
||||
<< ", samples=" << metrics.sample_count
|
||||
<< ", max_qd=" << metrics.max_velocity
|
||||
<< ", max_qdd=" << metrics.max_acceleration
|
||||
<< ", max_waypoint_error=" << metrics.max_waypoint_error
|
||||
<< ", start_error=" << metrics.start_error
|
||||
<< ", end_error=" << metrics.end_error
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
TEST(ToppraMultiWaypointTest, SmoothSevenDofPathScalesToThousandsOfWaypoints)
|
||||
{
|
||||
double reference_duration_s = 0.0;
|
||||
for (const std::size_t count : {10U, 100U, 300U, 1000U, 3000U}) {
|
||||
const auto metrics = planAndMeasure(makeSmoothWaypoints(count));
|
||||
printMetrics(count, metrics);
|
||||
ASSERT_TRUE(metrics.success) << "waypoint_count=" << count;
|
||||
EXPECT_GT(metrics.duration_s, 0.0) << "waypoint_count=" << count;
|
||||
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6)
|
||||
<< "waypoint_count=" << count;
|
||||
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5)
|
||||
<< "waypoint_count=" << count;
|
||||
EXPECT_LT(metrics.max_waypoint_error, 0.002)
|
||||
<< "waypoint_count=" << count;
|
||||
if (reference_duration_s == 0.0) {
|
||||
reference_duration_s = metrics.duration_s;
|
||||
} else {
|
||||
EXPECT_NEAR(metrics.duration_s, reference_duration_s,
|
||||
reference_duration_s * 0.10)
|
||||
<< "waypoint_count=" << count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ToppraMultiWaypointTest, RepeatedWaypointsRemainPlannable)
|
||||
{
|
||||
const auto smooth = makeSmoothWaypoints(300);
|
||||
std::vector<std::vector<double>> repeated;
|
||||
repeated.reserve(smooth.size() * 2);
|
||||
for (const auto& waypoint : smooth) {
|
||||
repeated.push_back(waypoint);
|
||||
repeated.push_back(waypoint);
|
||||
}
|
||||
|
||||
const auto metrics = planAndMeasure(repeated);
|
||||
printMetrics(repeated.size(), metrics);
|
||||
EXPECT_TRUE(metrics.success);
|
||||
if (metrics.success) {
|
||||
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6);
|
||||
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5);
|
||||
EXPECT_LT(metrics.max_waypoint_error, 0.002);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ToppraMultiWaypointTest, CompareInterpolationModesAtThreeHundredWaypoints)
|
||||
{
|
||||
const auto waypoints = makeSmoothWaypoints(300);
|
||||
for (const auto path_type : {
|
||||
PathType::CubicHermite,
|
||||
PathType::Quintic,
|
||||
PathType::Natural}) {
|
||||
const auto metrics = planAndMeasure(waypoints, path_type);
|
||||
std::cout << "[ToppraMultiWaypointTest] path_type="
|
||||
<< pathTypeName(path_type) << std::endl;
|
||||
printMetrics(waypoints.size(), metrics);
|
||||
EXPECT_TRUE(metrics.success) << pathTypeName(path_type);
|
||||
if (metrics.success) {
|
||||
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6)
|
||||
<< pathTypeName(path_type);
|
||||
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5)
|
||||
<< pathTypeName(path_type);
|
||||
EXPECT_LT(metrics.max_waypoint_error, 0.002)
|
||||
<< pathTypeName(path_type);
|
||||
EXPECT_LT(metrics.start_error, 1e-9) << pathTypeName(path_type);
|
||||
EXPECT_LT(metrics.end_error, 1e-9) << pathTypeName(path_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr
|
||||
@ -1,100 +0,0 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/10.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "s_curve_velocity_planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
struct SCurvePositionPlannerState
|
||||
{
|
||||
double position;
|
||||
double velocity;
|
||||
double acceleration;
|
||||
double jerk;
|
||||
double target_position;
|
||||
bool is_moving;
|
||||
|
||||
SCurvePositionPlannerState()
|
||||
: position(0.0)
|
||||
, velocity(0.0)
|
||||
, acceleration(0.0)
|
||||
, jerk(0.0)
|
||||
, target_position(0.0)
|
||||
, is_moving(false)
|
||||
{}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 单轴位置跟踪规划器
|
||||
*
|
||||
* 结构:
|
||||
* - 外环:position_error -> desired_velocity
|
||||
* - 内环:SCurveVelocityPlanner1D 负责 jerk-limited 速度规划
|
||||
*
|
||||
* 这个类用于高频变化目标的位置跟踪,不承担严格点到点 profile 语义。
|
||||
*/
|
||||
class SCurvePositionPlanner1D
|
||||
{
|
||||
public:
|
||||
SCurvePositionPlanner1D(double max_velocity = 3.0,
|
||||
double max_acceleration = 10.0,
|
||||
double max_jerk = 50.0);
|
||||
|
||||
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
|
||||
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
|
||||
|
||||
void setPositionGain(double position_gain);
|
||||
double getPositionGain() const { return position_gain_; }
|
||||
|
||||
void initialize(double position, double velocity = 0.0, double acceleration = 0.0);
|
||||
void reset();
|
||||
|
||||
void setTarget(double target_position);
|
||||
double update(double dt);
|
||||
|
||||
const SCurvePositionPlannerState& getState() const { return state_; }
|
||||
double getPosition() const { return state_.position; }
|
||||
double getVelocity() const { return state_.velocity; }
|
||||
double getAcceleration() const { return state_.acceleration; }
|
||||
double getJerk() const { return state_.jerk; }
|
||||
double getTargetPosition() const { return state_.target_position; }
|
||||
bool isMoving() const { return state_.is_moving; }
|
||||
|
||||
private:
|
||||
double max_velocity_;
|
||||
double max_acceleration_;
|
||||
double max_jerk_;
|
||||
|
||||
SCurvePositionPlannerState state_;
|
||||
SCurveVelocityPlanner1D velocity_planner_;
|
||||
double position_gain_;
|
||||
|
||||
static constexpr double EPSILON = 1e-9;
|
||||
static constexpr double VELOCITY_THRESHOLD = 1e-6;
|
||||
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
|
||||
static constexpr double POSITION_THRESHOLD = 1e-7;
|
||||
|
||||
double computeDesiredVelocity(double position_error) const;
|
||||
double computePlannerStoppingDistance(double velocity, double acceleration) const;
|
||||
|
||||
static double clamp(double value, double min_val, double max_val)
|
||||
{
|
||||
return std::max(min_val, std::min(max_val, value));
|
||||
}
|
||||
|
||||
static double sign(double value)
|
||||
{
|
||||
if (value > EPSILON) return 1.0;
|
||||
if (value < -EPSILON) return -1.0;
|
||||
return 0.0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,240 +0,0 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/9.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief 单次速度切换的 S 曲线剖面参数
|
||||
*
|
||||
* 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile:
|
||||
*
|
||||
* seg1: jerk = j1, duration = t1
|
||||
* seg2: jerk = j2, duration = t2 (当前实现 j2 = 0)
|
||||
* seg3: jerk = j3, duration = t3
|
||||
*
|
||||
* 其中 j1/j3 为 ±j_max,j2 为 0。
|
||||
*/
|
||||
struct SCurveVelocityProfile
|
||||
{
|
||||
double t1;
|
||||
double t2;
|
||||
double t3;
|
||||
|
||||
double total_time;
|
||||
|
||||
double j1;
|
||||
double j2;
|
||||
double j3;
|
||||
|
||||
double v0;
|
||||
double a0;
|
||||
double vf;
|
||||
|
||||
bool valid;
|
||||
|
||||
SCurveVelocityProfile()
|
||||
: t1(0.0), t2(0.0), t3(0.0)
|
||||
, total_time(0.0)
|
||||
, j1(0.0), j2(0.0), j3(0.0)
|
||||
, v0(0.0), a0(0.0), vf(0.0)
|
||||
, valid(false)
|
||||
{}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief S 曲线速度规划器状态
|
||||
*/
|
||||
struct SCurveVelocityPlannerState
|
||||
{
|
||||
double velocity;
|
||||
double acceleration;
|
||||
double jerk;
|
||||
|
||||
double target_velocity;
|
||||
|
||||
double elapsed_time;
|
||||
bool has_active_profile;
|
||||
bool is_moving;
|
||||
|
||||
SCurveVelocityPlannerState()
|
||||
: velocity(0.0)
|
||||
, acceleration(0.0)
|
||||
, jerk(0.0)
|
||||
, target_velocity(0.0)
|
||||
, elapsed_time(0.0)
|
||||
, has_active_profile(false)
|
||||
, is_moving(false)
|
||||
{}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 单轴速度型 S 曲线规划器
|
||||
*
|
||||
* 语义:
|
||||
* - setTargetVelocity(v): 设置新目标并重规划
|
||||
* - update(dt): 只采样当前 active profile
|
||||
* - overwriteState(v,a): 仅覆盖当前状态并清掉旧 profile
|
||||
* - synchronizeAndReplan(v,a): 用测量状态同步,并按当前目标重规划
|
||||
*
|
||||
* 数学目标:
|
||||
* - 从任意 (v0, a0) 连续规划到 (vf, 0)
|
||||
* - 满足 |v| <= v_max, |a| <= a_max, |j| <= j_max
|
||||
*/
|
||||
class SCurveVelocityPlanner1D
|
||||
{
|
||||
public:
|
||||
SCurveVelocityPlanner1D(double max_velocity = 1.0,
|
||||
double max_acceleration = 1.0,
|
||||
double max_jerk = 5.0);
|
||||
|
||||
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
|
||||
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
|
||||
|
||||
/**
|
||||
* @brief 设置目标变化阈值
|
||||
*
|
||||
* 目标变化量小于该阈值时,不触发重规划。
|
||||
*/
|
||||
void setTargetReplanThreshold(double threshold);
|
||||
|
||||
/**
|
||||
* @brief 设置同步反馈时的重规划阈值
|
||||
*
|
||||
* 测量速度与当前 profile 采样状态的偏差小于该阈值时,
|
||||
* synchronizeAndReplan() 只对齐当前状态,不打断现有 profile。
|
||||
*/
|
||||
void setSynchronizeReplanThreshold(double threshold);
|
||||
|
||||
void initialize(double velocity = 0.0, double acceleration = 0.0);
|
||||
void reset();
|
||||
|
||||
/**
|
||||
* @brief 仅覆盖当前状态,并清掉旧 profile
|
||||
*
|
||||
* 注意:
|
||||
* - 这个接口不会自动重规划
|
||||
* - 用于初始化、调试、或显式中断旧轨迹
|
||||
*/
|
||||
void overwriteState(double velocity,
|
||||
double acceleration = 0.0,
|
||||
bool keep_target_velocity = true);
|
||||
|
||||
/**
|
||||
* @brief 用测量状态同步,并按当前目标重新规划
|
||||
*
|
||||
* 这是闭环场景真正该用的接口。
|
||||
*/
|
||||
void synchronizeAndReplan(double velocity,
|
||||
double acceleration = 0.0);
|
||||
|
||||
/**
|
||||
* @brief 设置目标速度,并立即重规划
|
||||
*/
|
||||
void setTargetVelocity(double target_velocity);
|
||||
|
||||
/**
|
||||
* @brief 平滑停下
|
||||
*/
|
||||
void stop() { setTargetVelocity(0.0); }
|
||||
|
||||
/**
|
||||
* @brief 更新一步(只采样)
|
||||
* @param dt 时间步长
|
||||
* @return 当前采样后的速度
|
||||
*/
|
||||
double update(double dt);
|
||||
|
||||
/**
|
||||
* @brief 计算单次速度切换剖面
|
||||
*/
|
||||
SCurveVelocityProfile calculateProfile(double start_velocity,
|
||||
double end_velocity,
|
||||
double start_acceleration = 0.0) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的速度
|
||||
*/
|
||||
double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的加速度
|
||||
*/
|
||||
double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 给定剖面下,获取时刻 t 的 jerk
|
||||
*/
|
||||
double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const;
|
||||
|
||||
/**
|
||||
* @brief 按固定时间间隔生成轨迹点
|
||||
*/
|
||||
void generateTrajectory(const SCurveVelocityProfile& profile, double dt,
|
||||
std::vector<double>& velocities,
|
||||
std::vector<double>& accelerations,
|
||||
std::vector<double>& jerks) const;
|
||||
|
||||
const SCurveVelocityPlannerState& getState() const { return state_; }
|
||||
const SCurveVelocityProfile& getActiveProfile() const { return active_profile_; }
|
||||
|
||||
double getVelocity() const { return state_.velocity; }
|
||||
double getAcceleration() const { return state_.acceleration; }
|
||||
double getJerk() const { return state_.jerk; }
|
||||
double getTargetVelocity() const { return state_.target_velocity; }
|
||||
bool hasActiveProfile() const { return state_.has_active_profile; }
|
||||
bool isMoving() const { return state_.is_moving; }
|
||||
|
||||
private:
|
||||
double max_velocity_;
|
||||
double max_acceleration_;
|
||||
double max_jerk_;
|
||||
|
||||
double target_replan_threshold_;
|
||||
double synchronize_replan_threshold_;
|
||||
|
||||
SCurveVelocityPlannerState state_;
|
||||
SCurveVelocityProfile active_profile_;
|
||||
|
||||
static constexpr double EPSILON = 1e-9;
|
||||
static constexpr double VELOCITY_THRESHOLD = 1e-6;
|
||||
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
|
||||
static constexpr double DEFAULT_TARGET_REPLAN_THRESHOLD = 1e-9;
|
||||
static constexpr double DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD = 5e-2;
|
||||
|
||||
private:
|
||||
void updateIsMovingFlag();
|
||||
|
||||
/**
|
||||
* @brief 判断 profile 是否满足速度上限
|
||||
*/
|
||||
bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const;
|
||||
|
||||
/**
|
||||
* @brief 计算完整剖面终点状态
|
||||
*/
|
||||
void integrateWholeProfile(const SCurveVelocityProfile& profile,
|
||||
double& v_end,
|
||||
double& a_end) const;
|
||||
|
||||
static double clamp(double value, double min_val, double max_val)
|
||||
{
|
||||
return std::max(min_val, std::min(max_val, value));
|
||||
}
|
||||
|
||||
static double sign(double value)
|
||||
{
|
||||
if (value > EPSILON) return 1.0;
|
||||
if (value < -EPSILON) return -1.0;
|
||||
return 0.0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,191 +0,0 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/10.
|
||||
//
|
||||
|
||||
#include "../include/s_curve_position_planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
SCurvePositionPlanner1D::SCurvePositionPlanner1D(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
: max_velocity_(std::abs(max_velocity))
|
||||
, max_acceleration_(std::abs(max_acceleration))
|
||||
, max_jerk_(std::abs(max_jerk))
|
||||
, velocity_planner_(max_velocity_, max_acceleration_, max_jerk_)
|
||||
, position_gain_(1.0)
|
||||
{
|
||||
velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_));
|
||||
reset();
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::setConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
max_velocity_ = std::abs(max_velocity);
|
||||
max_acceleration_ = std::abs(max_acceleration);
|
||||
max_jerk_ = std::abs(max_jerk);
|
||||
velocity_planner_.setConstraints(max_velocity_, max_acceleration_, max_jerk_);
|
||||
velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_));
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::getConstraints(double& max_velocity,
|
||||
double& max_acceleration,
|
||||
double& max_jerk) const
|
||||
{
|
||||
max_velocity = max_velocity_;
|
||||
max_acceleration = max_acceleration_;
|
||||
max_jerk = max_jerk_;
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::setPositionGain(double position_gain)
|
||||
{
|
||||
position_gain_ = std::max(0.0, position_gain);
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::initialize(double position, double velocity, double acceleration)
|
||||
{
|
||||
state_.position = position;
|
||||
velocity_planner_.initialize(velocity, acceleration);
|
||||
state_.velocity = velocity_planner_.getVelocity();
|
||||
state_.acceleration = velocity_planner_.getAcceleration();
|
||||
state_.jerk = 0.0;
|
||||
state_.target_position = position;
|
||||
state_.is_moving = false;
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::reset()
|
||||
{
|
||||
state_ = SCurvePositionPlannerState();
|
||||
velocity_planner_.reset();
|
||||
}
|
||||
|
||||
void SCurvePositionPlanner1D::setTarget(double target_position)
|
||||
{
|
||||
state_.target_position = target_position;
|
||||
}
|
||||
|
||||
double SCurvePositionPlanner1D::update(double dt)
|
||||
{
|
||||
if (dt <= 0.0 || dt > 0.1) {
|
||||
return state_.position;
|
||||
}
|
||||
|
||||
const double position_error = state_.target_position - state_.position;
|
||||
if (std::abs(position_error) < POSITION_THRESHOLD &&
|
||||
std::abs(velocity_planner_.getVelocity()) < VELOCITY_THRESHOLD &&
|
||||
std::abs(velocity_planner_.getAcceleration()) < ACCELERATION_THRESHOLD) {
|
||||
velocity_planner_.overwriteState(0.0, 0.0, false);
|
||||
state_.position = state_.target_position;
|
||||
state_.velocity = 0.0;
|
||||
state_.acceleration = 0.0;
|
||||
state_.jerk = 0.0;
|
||||
state_.is_moving = false;
|
||||
return state_.position;
|
||||
}
|
||||
|
||||
velocity_planner_.setTargetVelocity(computeDesiredVelocity(position_error));
|
||||
|
||||
const double old_velocity = velocity_planner_.getVelocity();
|
||||
const double new_velocity = velocity_planner_.update(dt);
|
||||
|
||||
state_.velocity = new_velocity;
|
||||
state_.acceleration = velocity_planner_.getAcceleration();
|
||||
state_.jerk = velocity_planner_.getJerk();
|
||||
state_.position += 0.5 * (old_velocity + new_velocity) * dt;
|
||||
|
||||
const double updated_error = state_.target_position - state_.position;
|
||||
if (std::abs(updated_error) < POSITION_THRESHOLD &&
|
||||
std::abs(state_.velocity) < VELOCITY_THRESHOLD &&
|
||||
std::abs(state_.acceleration) < ACCELERATION_THRESHOLD) {
|
||||
velocity_planner_.overwriteState(0.0, 0.0, false);
|
||||
state_.position = state_.target_position;
|
||||
state_.velocity = 0.0;
|
||||
state_.acceleration = 0.0;
|
||||
state_.jerk = 0.0;
|
||||
state_.is_moving = false;
|
||||
return state_.position;
|
||||
}
|
||||
|
||||
state_.is_moving = velocity_planner_.isMoving() ||
|
||||
std::abs(updated_error) > POSITION_THRESHOLD;
|
||||
return state_.position;
|
||||
}
|
||||
|
||||
double SCurvePositionPlanner1D::computeDesiredVelocity(double position_error) const
|
||||
{
|
||||
if (std::abs(position_error) <= POSITION_THRESHOLD) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
const double proportional_velocity =
|
||||
clamp(position_gain_ * position_error, -max_velocity_, max_velocity_);
|
||||
const double current_velocity = velocity_planner_.getVelocity();
|
||||
const double current_acceleration = velocity_planner_.getAcceleration();
|
||||
const double stopping_distance =
|
||||
computePlannerStoppingDistance(current_velocity, current_acceleration);
|
||||
|
||||
if (std::abs(current_velocity) > VELOCITY_THRESHOLD &&
|
||||
sign(current_velocity) != sign(position_error)) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (std::abs(current_velocity) > VELOCITY_THRESHOLD &&
|
||||
sign(current_velocity) == sign(position_error) &&
|
||||
std::abs(position_error) <= std::abs(stopping_distance) * 1.05) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double low = 0.0;
|
||||
double high = max_velocity_;
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
const double mid = 0.5 * (low + high);
|
||||
const double distance =
|
||||
std::abs(computePlannerStoppingDistance(sign(position_error) * mid, 0.0));
|
||||
if (distance <= std::abs(position_error)) {
|
||||
low = mid;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
|
||||
return sign(position_error) *
|
||||
std::min(std::abs(proportional_velocity), low);
|
||||
}
|
||||
|
||||
double SCurvePositionPlanner1D::computePlannerStoppingDistance(double velocity,
|
||||
double acceleration) const
|
||||
{
|
||||
if (std::abs(velocity) <= VELOCITY_THRESHOLD &&
|
||||
std::abs(acceleration) <= ACCELERATION_THRESHOLD) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
const auto profile = velocity_planner_.calculateProfile(velocity, 0.0, acceleration);
|
||||
if (!profile.valid || profile.total_time <= EPSILON) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
const int steps = std::max(16, static_cast<int>(std::ceil(profile.total_time / 0.002)));
|
||||
const double dt = profile.total_time / static_cast<double>(steps);
|
||||
|
||||
double distance = 0.0;
|
||||
double previous_time = 0.0;
|
||||
double previous_velocity = velocity_planner_.getVelocityAtTime(profile, 0.0);
|
||||
for (int i = 1; i <= steps; ++i) {
|
||||
const double t = (i == steps) ? profile.total_time : i * dt;
|
||||
const double current_velocity = velocity_planner_.getVelocityAtTime(profile, t);
|
||||
distance += 0.5 * (previous_velocity + current_velocity) * (t - previous_time);
|
||||
previous_time = t;
|
||||
previous_velocity = current_velocity;
|
||||
}
|
||||
|
||||
return distance;
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,578 +0,0 @@
|
||||
//
|
||||
// Created by lgv on 2026/3/9.
|
||||
//
|
||||
|
||||
#include "../include/s_curve_velocity_planner.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace cmvr
|
||||
{
|
||||
|
||||
SCurveVelocityPlanner1D::SCurveVelocityPlanner1D(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
: max_velocity_(std::abs(max_velocity))
|
||||
, max_acceleration_(std::abs(max_acceleration))
|
||||
, max_jerk_(std::abs(max_jerk))
|
||||
, target_replan_threshold_(DEFAULT_TARGET_REPLAN_THRESHOLD)
|
||||
, synchronize_replan_threshold_(DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD)
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::setConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
max_velocity_ = std::abs(max_velocity);
|
||||
max_acceleration_ = std::abs(max_acceleration);
|
||||
max_jerk_ = std::abs(max_jerk);
|
||||
|
||||
state_.velocity = clamp(state_.velocity, -max_velocity_, max_velocity_);
|
||||
state_.acceleration = clamp(state_.acceleration, -max_acceleration_, max_acceleration_);
|
||||
state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_);
|
||||
|
||||
if (state_.has_active_profile) {
|
||||
active_profile_ = calculateProfile(state_.velocity,
|
||||
state_.target_velocity,
|
||||
state_.acceleration);
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON;
|
||||
}
|
||||
|
||||
updateIsMovingFlag();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::getConstraints(double& max_velocity,
|
||||
double& max_acceleration,
|
||||
double& max_jerk) const
|
||||
{
|
||||
max_velocity = max_velocity_;
|
||||
max_acceleration = max_acceleration_;
|
||||
max_jerk = max_jerk_;
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::setTargetReplanThreshold(double threshold)
|
||||
{
|
||||
target_replan_threshold_ = std::max(0.0, threshold);
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::setSynchronizeReplanThreshold(double threshold)
|
||||
{
|
||||
synchronize_replan_threshold_ = std::max(0.0, threshold);
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::initialize(double velocity, double acceleration)
|
||||
{
|
||||
state_ = SCurveVelocityPlannerState();
|
||||
state_.velocity = clamp(velocity, -max_velocity_, max_velocity_);
|
||||
state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_);
|
||||
state_.jerk = 0.0;
|
||||
state_.target_velocity = state_.velocity;
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = false;
|
||||
|
||||
active_profile_ = SCurveVelocityProfile();
|
||||
active_profile_.v0 = state_.velocity;
|
||||
active_profile_.a0 = state_.acceleration;
|
||||
active_profile_.vf = state_.velocity;
|
||||
active_profile_.valid = false;
|
||||
|
||||
updateIsMovingFlag();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::reset()
|
||||
{
|
||||
state_ = SCurveVelocityPlannerState();
|
||||
active_profile_ = SCurveVelocityProfile();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::overwriteState(double velocity,
|
||||
double acceleration,
|
||||
bool keep_target_velocity)
|
||||
{
|
||||
state_.velocity = clamp(velocity, -max_velocity_, max_velocity_);
|
||||
state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_);
|
||||
state_.jerk = 0.0;
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = false;
|
||||
|
||||
if (!keep_target_velocity) {
|
||||
state_.target_velocity = state_.velocity;
|
||||
} else {
|
||||
state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_);
|
||||
}
|
||||
|
||||
active_profile_ = SCurveVelocityProfile();
|
||||
active_profile_.v0 = state_.velocity;
|
||||
active_profile_.a0 = state_.acceleration;
|
||||
active_profile_.vf = state_.target_velocity;
|
||||
active_profile_.valid = false;
|
||||
|
||||
updateIsMovingFlag();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::synchronizeAndReplan(double velocity,
|
||||
double acceleration)
|
||||
{
|
||||
const double measured_velocity = clamp(velocity, -max_velocity_, max_velocity_);
|
||||
double measured_acceleration =
|
||||
clamp(acceleration, -max_acceleration_, max_acceleration_);
|
||||
|
||||
// When the target is zero this planner is also used for Cartesian speed
|
||||
// magnitudes. A magnitude is non-negative, while the finite-difference
|
||||
// derivative of the measured magnitude is signed. Feeding a large negative
|
||||
// measured acceleration into a signed 1-D velocity planner can generate a
|
||||
// profile that crosses through zero and becomes negative before returning to
|
||||
// zero. The twist limiter then multiplies that negative "norm" by the
|
||||
// current direction, which reverses and amplifies the Cartesian command.
|
||||
//
|
||||
// For feedback resynchronization during a stop, synchronize the measured
|
||||
// speed only and restart the stop profile with zero scalar acceleration.
|
||||
// This avoids noise-sensitive stop replans and preserves a non-overshooting
|
||||
// deceleration profile for speed-magnitude users.
|
||||
if (std::abs(state_.target_velocity) <= VELOCITY_THRESHOLD) {
|
||||
measured_acceleration = 0.0;
|
||||
}
|
||||
|
||||
if (!state_.has_active_profile &&
|
||||
std::abs(measured_velocity - state_.target_velocity) <= VELOCITY_THRESHOLD) {
|
||||
state_.velocity = state_.target_velocity;
|
||||
state_.acceleration = 0.0;
|
||||
state_.jerk = 0.0;
|
||||
updateIsMovingFlag();
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果测量值已经基本落在当前采样状态上,就继续沿现有 profile 走。
|
||||
// 否则每拍都从同一目标重规划,会把已经进入的 jerk phase 反复打断。
|
||||
if (state_.has_active_profile &&
|
||||
std::abs(measured_velocity - state_.velocity) <= synchronize_replan_threshold_) {
|
||||
state_.velocity = measured_velocity;
|
||||
state_.acceleration = measured_acceleration;
|
||||
state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time);
|
||||
updateIsMovingFlag();
|
||||
return;
|
||||
}
|
||||
|
||||
state_.velocity = measured_velocity;
|
||||
state_.acceleration = measured_acceleration;
|
||||
state_.jerk = 0.0;
|
||||
|
||||
active_profile_ = calculateProfile(state_.velocity,
|
||||
state_.target_velocity,
|
||||
state_.acceleration);
|
||||
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = active_profile_.total_time > EPSILON;
|
||||
|
||||
updateIsMovingFlag();
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::setTargetVelocity(double target_velocity)
|
||||
{
|
||||
const double new_target = clamp(target_velocity, -max_velocity_, max_velocity_);
|
||||
|
||||
const bool same_target =
|
||||
std::abs(new_target - state_.target_velocity) <= target_replan_threshold_;
|
||||
|
||||
if (same_target &&
|
||||
state_.has_active_profile) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (same_target &&
|
||||
!state_.has_active_profile &&
|
||||
std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD &&
|
||||
std::abs(state_.acceleration) <= ACCELERATION_THRESHOLD) {
|
||||
return;
|
||||
}
|
||||
|
||||
state_.target_velocity = new_target;
|
||||
|
||||
active_profile_ = calculateProfile(state_.velocity,
|
||||
state_.target_velocity,
|
||||
state_.acceleration);
|
||||
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON;
|
||||
|
||||
updateIsMovingFlag();
|
||||
}
|
||||
|
||||
double SCurveVelocityPlanner1D::getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return profile.v0;
|
||||
}
|
||||
|
||||
if (t <= 0.0) {
|
||||
return profile.v0;
|
||||
}
|
||||
if (t >= profile.total_time) {
|
||||
return profile.vf;
|
||||
}
|
||||
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
// seg1
|
||||
if (t <= profile.t1) {
|
||||
process_segment(t, profile.j1);
|
||||
return v;
|
||||
}
|
||||
process_segment(profile.t1, profile.j1);
|
||||
|
||||
// seg2
|
||||
const double t_after_1 = t - profile.t1;
|
||||
if (t_after_1 <= profile.t2) {
|
||||
process_segment(t_after_1, profile.j2);
|
||||
return v;
|
||||
}
|
||||
process_segment(profile.t2, profile.j2);
|
||||
|
||||
// seg3
|
||||
const double t_after_2 = t_after_1 - profile.t2;
|
||||
process_segment(t_after_2, profile.j3);
|
||||
return v;
|
||||
}
|
||||
|
||||
double SCurveVelocityPlanner1D::getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return profile.a0;
|
||||
}
|
||||
|
||||
if (t <= 0.0) {
|
||||
return profile.a0;
|
||||
}
|
||||
if (t >= profile.total_time) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
// seg1
|
||||
if (t <= profile.t1) {
|
||||
process_segment(t, profile.j1);
|
||||
return a;
|
||||
}
|
||||
process_segment(profile.t1, profile.j1);
|
||||
|
||||
// seg2
|
||||
const double t_after_1 = t - profile.t1;
|
||||
if (t_after_1 <= profile.t2) {
|
||||
process_segment(t_after_1, profile.j2);
|
||||
return a;
|
||||
}
|
||||
process_segment(profile.t2, profile.j2);
|
||||
|
||||
// seg3
|
||||
const double t_after_2 = t_after_1 - profile.t2;
|
||||
process_segment(t_after_2, profile.j3);
|
||||
return a;
|
||||
}
|
||||
|
||||
double SCurveVelocityPlanner1D::getJerkAtTime(const SCurveVelocityProfile& profile, double t) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (t <= 0.0 || t >= profile.total_time) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (t <= profile.t1) {
|
||||
return profile.j1;
|
||||
}
|
||||
if (t <= profile.t1 + profile.t2) {
|
||||
return profile.j2;
|
||||
}
|
||||
return profile.j3;
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::integrateWholeProfile(const SCurveVelocityProfile& profile,
|
||||
double& v_end,
|
||||
double& a_end) const
|
||||
{
|
||||
double v = profile.v0;
|
||||
double a = profile.a0;
|
||||
|
||||
auto process_segment = [&](double dt, double jerk) {
|
||||
v += a * dt + 0.5 * jerk * dt * dt;
|
||||
a += jerk * dt;
|
||||
};
|
||||
|
||||
process_segment(profile.t1, profile.j1);
|
||||
process_segment(profile.t2, profile.j2);
|
||||
process_segment(profile.t3, profile.j3);
|
||||
|
||||
v_end = v;
|
||||
a_end = a;
|
||||
}
|
||||
|
||||
bool SCurveVelocityPlanner1D::isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const
|
||||
{
|
||||
if (!profile.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<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;
|
||||
}
|
||||
|
||||
SCurveVelocityProfile SCurveVelocityPlanner1D::calculateProfile(double start_velocity,
|
||||
double end_velocity,
|
||||
double start_acceleration) const
|
||||
{
|
||||
SCurveVelocityProfile best;
|
||||
best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_);
|
||||
best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_);
|
||||
best.vf = clamp(end_velocity, -max_velocity_, max_velocity_);
|
||||
|
||||
if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) {
|
||||
// 退化情况:这里不做特殊退化规划,直接返回 invalid
|
||||
return best;
|
||||
}
|
||||
|
||||
const double v0 = best.v0;
|
||||
const double a0 = best.a0;
|
||||
const double vf = best.vf;
|
||||
|
||||
// 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0”
|
||||
double s = sign(vf - v0);
|
||||
if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) {
|
||||
s = 1.0;
|
||||
}
|
||||
|
||||
const double dv = s * (vf - v0); // >= 0
|
||||
const double a0s = s * a0; // signed frame 下的初始 acceleration
|
||||
const double j = max_jerk_;
|
||||
const double amax = max_acceleration_;
|
||||
|
||||
auto normalize_nonnegative = [](double x) {
|
||||
return (x < 0.0 && x > -1e-10) ? 0.0 : x;
|
||||
};
|
||||
|
||||
auto try_candidate = [&](double t1, double t2, double t3,
|
||||
double j1s, double j2s, double j3s) {
|
||||
t1 = normalize_nonnegative(t1);
|
||||
t2 = normalize_nonnegative(t2);
|
||||
t3 = normalize_nonnegative(t3);
|
||||
|
||||
if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) {
|
||||
return;
|
||||
}
|
||||
|
||||
SCurveVelocityProfile cand;
|
||||
cand.t1 = t1;
|
||||
cand.t2 = t2;
|
||||
cand.t3 = t3;
|
||||
cand.total_time = t1 + t2 + t3;
|
||||
|
||||
cand.j1 = s * j1s;
|
||||
cand.j2 = s * j2s;
|
||||
cand.j3 = s * j3s;
|
||||
|
||||
cand.v0 = v0;
|
||||
cand.a0 = a0;
|
||||
cand.vf = vf;
|
||||
cand.valid = true;
|
||||
|
||||
double vend = 0.0;
|
||||
double aend = 0.0;
|
||||
integrateWholeProfile(cand, vend, aend);
|
||||
|
||||
if (std::abs(vend - vf) > 1e-5) {
|
||||
return;
|
||||
}
|
||||
if (std::abs(aend) > 1e-5) {
|
||||
return;
|
||||
}
|
||||
if (!isVelocityLimitSatisfied(cand)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!best.valid || cand.total_time < best.total_time) {
|
||||
best = cand;
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------- UDU 三角形(无平台) ----------------
|
||||
{
|
||||
// Δv = (2A^2 - a0^2)/(2j)
|
||||
const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s);
|
||||
if (A2 >= -1e-10) {
|
||||
const double A = std::sqrt(std::max(0.0, A2));
|
||||
if (A <= amax + 1e-10 && A >= a0s - 1e-10) {
|
||||
const double t1 = (A - a0s) / j;
|
||||
const double t2 = 0.0;
|
||||
const double t3 = A / j;
|
||||
try_candidate(t1, t2, t3, +j, 0.0, -j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- UDU 梯形(有平台) ----------------
|
||||
{
|
||||
const double A = amax;
|
||||
if (A > EPSILON && A >= a0s - 1e-10) {
|
||||
const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j);
|
||||
const double t1 = (A - a0s) / j;
|
||||
const double t2 = (dv - base) / A;
|
||||
const double t3 = A / j;
|
||||
try_candidate(t1, t2, t3, +j, 0.0, -j);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- DUD 三角形(无平台) ----------------
|
||||
{
|
||||
// Δv = (a0^2 - 2B^2)/(2j)
|
||||
const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv);
|
||||
if (B2 >= -1e-10) {
|
||||
const double B = std::sqrt(std::max(0.0, B2));
|
||||
if (B <= amax + 1e-10 && B >= -a0s - 1e-10) {
|
||||
const double t1 = (a0s + B) / j;
|
||||
const double t2 = 0.0;
|
||||
const double t3 = B / j;
|
||||
try_candidate(t1, t2, t3, -j, 0.0, +j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- DUD 梯形(有平台) ----------------
|
||||
{
|
||||
const double B = amax;
|
||||
if (B > EPSILON && B >= -a0s - 1e-10) {
|
||||
const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j);
|
||||
const double t1 = (a0s + B) / j;
|
||||
const double t2 = (base - dv) / B;
|
||||
const double t3 = B / j;
|
||||
try_candidate(t1, t2, t3, -j, 0.0, +j);
|
||||
}
|
||||
}
|
||||
|
||||
// 已到终点附近
|
||||
if (!best.valid &&
|
||||
std::abs(vf - v0) <= VELOCITY_THRESHOLD &&
|
||||
std::abs(a0) <= ACCELERATION_THRESHOLD) {
|
||||
best.valid = false;
|
||||
best.total_time = 0.0;
|
||||
best.v0 = v0;
|
||||
best.a0 = a0;
|
||||
best.vf = vf;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::generateTrajectory(const SCurveVelocityProfile& profile, double dt,
|
||||
std::vector<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);
|
||||
}
|
||||
}
|
||||
|
||||
double SCurveVelocityPlanner1D::update(double dt)
|
||||
{
|
||||
if (dt <= 0.0) {
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
if (!state_.has_active_profile || !active_profile_.valid) {
|
||||
state_.jerk = 0.0;
|
||||
updateIsMovingFlag();
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
state_.elapsed_time += dt;
|
||||
|
||||
if (state_.elapsed_time >= active_profile_.total_time) {
|
||||
state_.elapsed_time = active_profile_.total_time;
|
||||
state_.velocity = active_profile_.vf;
|
||||
state_.acceleration = 0.0;
|
||||
state_.jerk = 0.0;
|
||||
state_.has_active_profile = false;
|
||||
updateIsMovingFlag();
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
state_.velocity = getVelocityAtTime(active_profile_, state_.elapsed_time);
|
||||
state_.acceleration = getAccelerationAtTime(active_profile_, state_.elapsed_time);
|
||||
state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time);
|
||||
|
||||
updateIsMovingFlag();
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
void SCurveVelocityPlanner1D::updateIsMovingFlag()
|
||||
{
|
||||
state_.is_moving =
|
||||
state_.has_active_profile ||
|
||||
std::abs(state_.velocity) > VELOCITY_THRESHOLD ||
|
||||
std::abs(state_.target_velocity) > VELOCITY_THRESHOLD ||
|
||||
std::abs(state_.acceleration) > ACCELERATION_THRESHOLD;
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -1,77 +0,0 @@
|
||||
#include <algorithm>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h"
|
||||
|
||||
namespace cmvr {
|
||||
namespace {
|
||||
|
||||
void finishActiveProfile(SCurveVelocityPlanner1D& planner, double dt)
|
||||
{
|
||||
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
|
||||
planner.update(dt);
|
||||
}
|
||||
ASSERT_FALSE(planner.hasActiveProfile());
|
||||
}
|
||||
|
||||
TEST(SCurveVelocityPlannerStopTest, FeedbackResyncDoesNotReverseSpeedMagnitude)
|
||||
{
|
||||
SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0);
|
||||
constexpr double kDt = 0.001;
|
||||
constexpr double kInitialSpeed = 0.04;
|
||||
|
||||
planner.initialize(kInitialSpeed, 0.0);
|
||||
planner.setTargetVelocity(0.0);
|
||||
finishActiveProfile(planner, kDt);
|
||||
|
||||
// Reproduce the speedL stop feedback case: the command profile has already
|
||||
// reached zero, but the measured TCP still has residual speed. A 1 kHz
|
||||
// finite difference may report a large negative scalar acceleration.
|
||||
planner.synchronizeAndReplan(kInitialSpeed, -3.0);
|
||||
|
||||
double max_speed = planner.getVelocity();
|
||||
double min_speed = planner.getVelocity();
|
||||
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
|
||||
const double speed = planner.update(kDt);
|
||||
max_speed = std::max(max_speed, speed);
|
||||
min_speed = std::min(min_speed, speed);
|
||||
}
|
||||
|
||||
EXPECT_GE(min_speed, -1e-9);
|
||||
EXPECT_LE(max_speed, kInitialSpeed + 1e-9);
|
||||
EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(SCurveVelocityPlannerStopTest, LargerMeasuredDecelerationDoesNotIncreaseStopSpeed)
|
||||
{
|
||||
constexpr double kDt = 0.001;
|
||||
constexpr double kInitialSpeed = 0.04;
|
||||
const double measured_accelerations[] = {-0.5, -1.0, -2.0, -3.0};
|
||||
|
||||
for (const double measured_acceleration : measured_accelerations) {
|
||||
SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0);
|
||||
planner.initialize(kInitialSpeed, 0.0);
|
||||
planner.setTargetVelocity(0.0);
|
||||
finishActiveProfile(planner, kDt);
|
||||
|
||||
planner.synchronizeAndReplan(kInitialSpeed, measured_acceleration);
|
||||
|
||||
double max_speed = planner.getVelocity();
|
||||
double min_speed = planner.getVelocity();
|
||||
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
|
||||
const double speed = planner.update(kDt);
|
||||
max_speed = std::max(max_speed, speed);
|
||||
min_speed = std::min(min_speed, speed);
|
||||
}
|
||||
|
||||
EXPECT_GE(min_speed, -1e-9) << "measured_acceleration=" << measured_acceleration;
|
||||
EXPECT_LE(max_speed, kInitialSpeed + 1e-9)
|
||||
<< "measured_acceleration=" << measured_acceleration;
|
||||
EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9)
|
||||
<< "measured_acceleration=" << measured_acceleration;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr
|
||||
49
cmvr-es/algorithms/planner/CMakeLists.txt
Normal file
49
cmvr-es/algorithms/planner/CMakeLists.txt
Normal file
@ -0,0 +1,49 @@
|
||||
add_library(base_motion SHARED
|
||||
cartesian/s_curve/src/s_curve_planner.cpp)
|
||||
target_include_directories(base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(base_motion PUBLIC
|
||||
cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common)
|
||||
add_library(cmvr_es::base_motion ALIAS base_motion)
|
||||
install(TARGETS base_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_library(arm_motion SHARED
|
||||
cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp
|
||||
cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp)
|
||||
target_include_directories(arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(arm_motion PUBLIC
|
||||
cmvr_es::ik_solver cmvr_es::base_motion cmvr_es::curves)
|
||||
add_library(cmvr_es::arm_motion ALIAS arm_motion)
|
||||
add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion)
|
||||
install(TARGETS arm_motion LIBRARY DESTINATION lib)
|
||||
|
||||
add_library(joint_path_planner SHARED
|
||||
joint/ompl/src/rrt_connect.cpp)
|
||||
target_include_directories(joint_path_planner PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
|
||||
target_link_libraries(joint_path_planner PUBLIC cmvr_es::proto PRIVATE ompl)
|
||||
add_library(cmvr_es::joint_path_planner ALIAS joint_path_planner)
|
||||
install(TARGETS joint_path_planner LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(s_curve_planner_reversal_test
|
||||
cartesian/s_curve/test/s_curve_planner_reversal_test.cpp)
|
||||
target_link_libraries(s_curve_planner_reversal_test PRIVATE
|
||||
cmvr_es::base_motion gtest gtest_main)
|
||||
|
||||
add_executable(pinocchio_speedl_limits_test
|
||||
cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp)
|
||||
target_compile_definitions(pinocchio_speedl_limits_test PRIVATE
|
||||
CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(pinocchio_speedl_limits_test PRIVATE
|
||||
cmvr_es::algorithms::arm_motion gtest gtest_main)
|
||||
|
||||
add_executable(rrt_connect_test
|
||||
joint/ompl/test/rrt_connect_test.cpp)
|
||||
target_link_libraries(rrt_connect_test PRIVATE
|
||||
cmvr_es::joint_path_planner ompl gtest pthread)
|
||||
|
||||
add_executable(rrt_connect_self_collision_test
|
||||
joint/ompl/test/rrt_connect_self_collision_test.cpp)
|
||||
target_compile_definitions(rrt_connect_self_collision_test PRIVATE
|
||||
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
|
||||
target_link_libraries(rrt_connect_self_collision_test PRIVATE
|
||||
cmvr_es::joint_path_planner cmvr_es::collision_checker
|
||||
ompl gtest pthread)
|
||||
@ -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::SCurvePlanner 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::SCurve curve(velocity, acceleration, jerk);
|
||||
const cmvr::SCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0);
|
||||
if (profile.total_time <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
const auto reserve_count =
|
||||
static_cast<std::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 CartesianFrame
|
||||
{
|
||||
Base = 0,
|
||||
Tool = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 基于 SCurve 的六维末端在线速度规划器。
|
||||
*
|
||||
* initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。
|
||||
* 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。
|
||||
* 非连续模式与角速度近反向时,先停稳再反向。
|
||||
* 传入零目标平滑停止;相同目标会继续当前曲线,不会每拍重规划。
|
||||
* 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。
|
||||
* 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。
|
||||
*/
|
||||
class SCurvePlanner
|
||||
{
|
||||
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, CartesianFrame frame,
|
||||
double dt, const Eigen::Matrix3d& base_R_tool);
|
||||
|
||||
const Twist& getTwistBase() const { return twist_base_; }
|
||||
const Twist& getAccelerationBase() const { return acceleration_base_; }
|
||||
const Twist& getJerkBase() const { return jerk_base_; }
|
||||
bool isMoving() const;
|
||||
|
||||
private:
|
||||
static constexpr double EPSILON = 1e-12;
|
||||
static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999;
|
||||
|
||||
// 保存一维速度曲线的运行状态;数学计算由 SCurve 完成。
|
||||
struct VelocityState {
|
||||
struct Sample {
|
||||
double velocity{0.0};
|
||||
double acceleration{0.0};
|
||||
double target_velocity{0.0};
|
||||
double elapsed_time{0.0};
|
||||
bool has_active_profile{false};
|
||||
};
|
||||
|
||||
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
|
||||
void setTargetReplanThreshold(double threshold);
|
||||
void initialize(double velocity = 0.0, double acceleration = 0.0);
|
||||
void setTargetVelocity(double target_velocity);
|
||||
double update(double dt);
|
||||
|
||||
double getVelocity() const { return state_.velocity; }
|
||||
double getAcceleration() const { return state_.acceleration; }
|
||||
double replanThreshold() const { return target_replan_threshold_; }
|
||||
std::array<double, 3> limits() const;
|
||||
bool isSettled() const;
|
||||
bool isMoving() const;
|
||||
|
||||
private:
|
||||
void replan();
|
||||
|
||||
SCurve curve_{1.0, 1.0, 5.0};
|
||||
Sample state_;
|
||||
SCurveVelocityProfile active_profile_;
|
||||
double target_replan_threshold_{1e-9};
|
||||
static constexpr double VELOCITY_THRESHOLD = 1e-6;
|
||||
};
|
||||
|
||||
// Cubic Bezier velocity: endpoint accelerations are a0 and zero.
|
||||
// Derivative control-point norms certify complete v/a/j bounds.
|
||||
struct DirectionProfile {
|
||||
std::array<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::SCurvePlanner& planner,
|
||||
const config::SpeedLPlannerConfig& config)
|
||||
{
|
||||
using cmvr::common::config::positiveOr;
|
||||
|
||||
// Zero retains the protobuf default; reject bad values before changing the planner.
|
||||
for (const double value : {config.linear_velocity_max(), config.linear_acceleration_max(),
|
||||
config.linear_jerk_max(), config.angular_velocity_max(),
|
||||
config.angular_acceleration_max(), config.angular_jerk_max(),
|
||||
config.linear_target_replan_threshold(),
|
||||
config.angular_target_replan_threshold()}) {
|
||||
if (!std::isfinite(value) || value < 0.0) {
|
||||
throw std::invalid_argument("speedL limits and thresholds must be finite and non-negative");
|
||||
}
|
||||
}
|
||||
|
||||
planner.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
|
||||
positiveOr(config.linear_acceleration_max(), 5.0),
|
||||
positiveOr(config.linear_jerk_max(), 10.0));
|
||||
planner.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
|
||||
positiveOr(config.angular_acceleration_max(), 5.0),
|
||||
positiveOr(config.angular_jerk_max(), 12.0));
|
||||
planner.setLinearTargetReplanThreshold(
|
||||
positiveOr(config.linear_target_replan_threshold(), 1e-4));
|
||||
planner.setAngularTargetReplanThreshold(
|
||||
positiveOr(config.angular_target_replan_threshold(), 1e-4));
|
||||
planner.setContinuousLinearReversal(!config.has_continuous_linear_reversal() ||
|
||||
config.continuous_linear_reversal());
|
||||
planner.initialize(Eigen::Matrix<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)
|
||||
{
|
||||
// SCurve's solver treats acceleration/jerk <= 1e-9 as degenerate.
|
||||
if (!std::isfinite(velocity) || velocity <= 1e-9 ||
|
||||
!std::isfinite(acceleration) || acceleration <= 1e-9 ||
|
||||
!std::isfinite(jerk) || jerk <= 1e-9) {
|
||||
throw std::invalid_argument("S-curve limits must be finite and greater than 1e-9");
|
||||
}
|
||||
}
|
||||
|
||||
bool withinLimit(double value, double limit)
|
||||
{
|
||||
return std::isfinite(value) && value <= limit * (1.0 + 1e-10);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::array<double, 3> SCurvePlanner::VelocityState::limits() const
|
||||
{
|
||||
std::array<double, 3> result;
|
||||
curve_.getConstraints(result[0], result[1], result[2]);
|
||||
return result;
|
||||
}
|
||||
|
||||
void SCurvePlanner::VelocityState::setConstraints(double max_velocity,
|
||||
double max_acceleration,
|
||||
double max_jerk)
|
||||
{
|
||||
validateLimits(max_velocity, max_acceleration, max_jerk);
|
||||
if (!withinLimit(std::abs(state_.velocity), max_velocity) ||
|
||||
!withinLimit(std::abs(state_.acceleration), max_acceleration)) {
|
||||
throw std::invalid_argument("S-curve limits exclude the current velocity or acceleration");
|
||||
}
|
||||
if (limits() == std::array<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 SCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold)
|
||||
{
|
||||
if (!std::isfinite(threshold) || threshold < 0.0) {
|
||||
throw std::invalid_argument("S-curve replan threshold must be nonnegative and finite");
|
||||
}
|
||||
target_replan_threshold_ = threshold;
|
||||
}
|
||||
|
||||
void SCurvePlanner::VelocityState::initialize(double velocity, double acceleration)
|
||||
{
|
||||
const auto bounds = limits();
|
||||
if (!withinLimit(std::abs(velocity), bounds[0]) ||
|
||||
!withinLimit(std::abs(acceleration), bounds[1])) {
|
||||
throw std::invalid_argument("S-curve initial velocity or acceleration exceeds limits");
|
||||
}
|
||||
state_ = Sample{};
|
||||
state_.velocity = velocity;
|
||||
state_.acceleration = acceleration;
|
||||
state_.target_velocity = velocity;
|
||||
active_profile_ = SCurveVelocityProfile();
|
||||
}
|
||||
|
||||
void SCurvePlanner::VelocityState::setTargetVelocity(double target_velocity)
|
||||
{
|
||||
const double velocity_limit = limits()[0];
|
||||
const double new_target = std::clamp(target_velocity, -velocity_limit, velocity_limit);
|
||||
const bool same_target =
|
||||
std::abs(new_target - state_.target_velocity) <= target_replan_threshold_;
|
||||
if (same_target && (state_.has_active_profile ||
|
||||
(std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0))) return;
|
||||
|
||||
state_.target_velocity = new_target;
|
||||
replan();
|
||||
}
|
||||
|
||||
void SCurvePlanner::VelocityState::replan()
|
||||
{
|
||||
const auto candidate = curve_.calculateVelocityProfile(
|
||||
state_.velocity, state_.target_velocity, state_.acceleration);
|
||||
const double values[] = {candidate.t1, candidate.t2, candidate.t3,
|
||||
candidate.total_time, candidate.j1, candidate.j2, candidate.j3,
|
||||
candidate.v0, candidate.a0, candidate.vf};
|
||||
const bool finite = std::all_of(std::begin(values), std::end(values),
|
||||
[](double value) { return std::isfinite(value); });
|
||||
if (!finite || !candidate.valid || candidate.total_time <= 0.0 ||
|
||||
candidate.t1 < 0.0 || candidate.t2 < 0.0 || candidate.t3 < 0.0) {
|
||||
if (finite && std::abs(state_.velocity - state_.target_velocity) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0) {
|
||||
state_.has_active_profile = false;
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error("S-curve could not generate a finite feasible velocity profile");
|
||||
}
|
||||
// The mathematical solver must not silently clamp the starting state.
|
||||
if (std::abs(candidate.v0 - state_.velocity) > 1e-12 ||
|
||||
std::abs(candidate.a0 - state_.acceleration) > 1e-12) {
|
||||
throw std::runtime_error("S-curve profile changed its initial state");
|
||||
}
|
||||
active_profile_ = candidate;
|
||||
state_.elapsed_time = 0.0;
|
||||
state_.has_active_profile = true;
|
||||
}
|
||||
|
||||
double SCurvePlanner::VelocityState::update(double dt)
|
||||
{
|
||||
if (!state_.has_active_profile) {
|
||||
if (state_.acceleration != 0.0 ||
|
||||
std::abs(state_.velocity - state_.target_velocity) > VELOCITY_THRESHOLD) {
|
||||
throw std::runtime_error("S-curve has no active profile for a moving transition");
|
||||
}
|
||||
return state_.velocity;
|
||||
}
|
||||
state_.elapsed_time = std::min(state_.elapsed_time + dt, active_profile_.total_time);
|
||||
if (state_.elapsed_time >= active_profile_.total_time) {
|
||||
state_.velocity = active_profile_.vf;
|
||||
state_.acceleration = 0.0;
|
||||
state_.has_active_profile = false;
|
||||
} else {
|
||||
state_.velocity = curve_.getVelocityAtTime(active_profile_, state_.elapsed_time);
|
||||
state_.acceleration = curve_.getAccelerationAtTime(active_profile_, state_.elapsed_time);
|
||||
}
|
||||
if (!std::isfinite(state_.velocity) || !std::isfinite(state_.acceleration)) {
|
||||
throw std::runtime_error("S-curve produced a non-finite state");
|
||||
}
|
||||
return state_.velocity;
|
||||
}
|
||||
|
||||
bool SCurvePlanner::VelocityState::isSettled() const
|
||||
{
|
||||
return !state_.has_active_profile &&
|
||||
std::abs(state_.velocity) <= VELOCITY_THRESHOLD &&
|
||||
state_.acceleration == 0.0;
|
||||
}
|
||||
|
||||
bool SCurvePlanner::VelocityState::isMoving() const
|
||||
{
|
||||
return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD;
|
||||
}
|
||||
|
||||
std::pair<Eigen::Vector3d, Eigen::Vector3d>
|
||||
SCurvePlanner::DirectionProfile::sample(double time) const
|
||||
{
|
||||
const double u = std::clamp(time / duration, 0.0, 1.0);
|
||||
const double r = 1.0 - u;
|
||||
const Eigen::Vector3d velocity = r*r*r*control[0] + 3*r*r*u*control[1] +
|
||||
3*r*u*u*control[2] + u*u*u*control[3];
|
||||
const Eigen::Vector3d acceleration = (3.0 / duration) *
|
||||
(r*r*(control[1]-control[0]) + 2*r*u*(control[2]-control[1]) +
|
||||
u*u*(control[3]-control[2]));
|
||||
return {velocity, acceleration};
|
||||
}
|
||||
|
||||
bool SCurvePlanner::DirectionProfile::fits(const std::array<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;
|
||||
}
|
||||
|
||||
SCurvePlanner::DirectionProfile SCurvePlanner::DirectionProfile::remaining() const
|
||||
{
|
||||
auto result = *this;
|
||||
auto work = control;
|
||||
const double u = std::clamp(elapsed / duration, 0.0, 1.0);
|
||||
for (std::size_t level = 1; level < control.size(); ++level) {
|
||||
for (std::size_t i = 0; i < control.size() - level; ++i) {
|
||||
work[i] = (1.0 - u) * work[i] + u * work[i+1];
|
||||
}
|
||||
result.control[control.size()-level-1] = work[control.size()-level-1];
|
||||
}
|
||||
result.duration -= elapsed;
|
||||
result.elapsed = 0.0;
|
||||
return result;
|
||||
}
|
||||
|
||||
void SCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile,
|
||||
double velocity, double acceleration, double jerk)
|
||||
{
|
||||
validateLimits(velocity, acceleration, jerk);
|
||||
if (scalar.limits() == std::array<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 SCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk)
|
||||
{
|
||||
setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk);
|
||||
}
|
||||
|
||||
void SCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk)
|
||||
{
|
||||
setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk);
|
||||
}
|
||||
|
||||
void SCurvePlanner::setLinearTargetReplanThreshold(double threshold)
|
||||
{
|
||||
linear_velocity_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void SCurvePlanner::setAngularTargetReplanThreshold(double threshold)
|
||||
{
|
||||
angular_velocity_.setTargetReplanThreshold(threshold);
|
||||
}
|
||||
|
||||
void SCurvePlanner::setContinuousLinearReversal(bool enabled)
|
||||
{
|
||||
if (continuous_linear_reversal_ == enabled) return;
|
||||
if (!enabled && !linear_direction_profile_.active) {
|
||||
const double velocity = linear_velocity_.getVelocity();
|
||||
const double acceleration = linear_velocity_.getAcceleration();
|
||||
if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) {
|
||||
linear_velocity_.initialize(-velocity, -acceleration);
|
||||
current_linear_dir_base_ = -current_linear_dir_base_;
|
||||
}
|
||||
}
|
||||
if (enabled) linear_direction_profile_.stopping_for_reversal = false;
|
||||
continuous_linear_reversal_ = enabled;
|
||||
}
|
||||
|
||||
void SCurvePlanner::initialize(const Twist& initial_twist)
|
||||
{
|
||||
const Eigen::Vector3d v0 = initial_twist.head<3>();
|
||||
const Eigen::Vector3d w0 = initial_twist.tail<3>();
|
||||
const double v0_norm = v0.norm();
|
||||
const double w0_norm = w0.norm();
|
||||
if (!initial_twist.allFinite() || !std::isfinite(v0_norm) || !std::isfinite(w0_norm)) {
|
||||
throw std::invalid_argument("S-curve initial twist must be finite");
|
||||
}
|
||||
auto staged = *this;
|
||||
staged.linear_velocity_.initialize(v0_norm, 0.0);
|
||||
staged.angular_velocity_.initialize(w0_norm, 0.0);
|
||||
staged.linear_direction_profile_ = DirectionProfile{};
|
||||
staged.angular_direction_profile_ = DirectionProfile{};
|
||||
staged.twist_base_ = initial_twist;
|
||||
staged.acceleration_base_.setZero();
|
||||
staged.jerk_base_.setZero();
|
||||
staged.previous_period_ = 0.0;
|
||||
staged.current_linear_dir_base_.setZero();
|
||||
staged.current_angular_dir_base_.setZero();
|
||||
if (v0_norm > EPSILON) staged.current_linear_dir_base_ = v0 / v0_norm;
|
||||
if (w0_norm > EPSILON) staged.current_angular_dir_base_ = w0 / w0_norm;
|
||||
*this = std::move(staged);
|
||||
}
|
||||
|
||||
bool SCurvePlanner::planDirection(const Eigen::Vector3d& velocity,
|
||||
const Eigen::Vector3d& acceleration,
|
||||
const Eigen::Vector3d& target, double dt,
|
||||
const std::array<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 SCurvePlanner::planVelocity(VelocityState& scalar,
|
||||
DirectionProfile& profile,
|
||||
Eigen::Vector3d& direction,
|
||||
const Eigen::Vector3d& target, double dt,
|
||||
bool continuous_reversal)
|
||||
{
|
||||
const auto bounds = scalar.limits();
|
||||
Eigen::Vector3d desired = target;
|
||||
const double target_norm = target.norm();
|
||||
if (target_norm > bounds[0]) desired *= bounds[0] / target_norm;
|
||||
|
||||
Eigen::Vector3d velocity = direction * scalar.getVelocity();
|
||||
Eigen::Vector3d acceleration = direction * scalar.getAcceleration();
|
||||
if (profile.active) {
|
||||
const auto state = profile.sample(profile.elapsed);
|
||||
velocity = state.first;
|
||||
acceleration = state.second;
|
||||
if (!continuous_reversal && velocity.norm() > EPSILON && desired.norm() > EPSILON &&
|
||||
velocity.normalized().dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD) {
|
||||
profile.stopping_for_reversal = true;
|
||||
}
|
||||
}
|
||||
if (profile.stopping_for_reversal) desired.setZero();
|
||||
|
||||
if (!profile.active) {
|
||||
if (velocity.isZero(0.0) && acceleration.isZero(0.0)) {
|
||||
if (desired.norm() > EPSILON) direction = desired.normalized();
|
||||
scalar.setTargetVelocity(desired.norm());
|
||||
return direction * scalar.update(dt);
|
||||
}
|
||||
const double signed_target = direction.dot(desired);
|
||||
const bool collinear = (desired - signed_target * direction).norm() <=
|
||||
1e-12 * desired.norm();
|
||||
const bool reverse = desired.norm() > EPSILON &&
|
||||
direction.dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD;
|
||||
if (desired.norm() <= EPSILON || (!continuous_reversal && reverse) ||
|
||||
(collinear && (continuous_reversal || signed_target >= 0.0))) {
|
||||
scalar.setTargetVelocity((!continuous_reversal && reverse) ? 0.0 : signed_target);
|
||||
const auto result = direction * scalar.update(dt);
|
||||
if (profile.stopping_for_reversal && scalar.isSettled()) {
|
||||
profile.stopping_for_reversal = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (!profile.active ||
|
||||
(desired - profile.control.back()).norm() > scalar.replanThreshold()) {
|
||||
if (planDirection(velocity, acceleration, desired, dt, bounds, profile)) {
|
||||
scalar.initialize();
|
||||
}
|
||||
}
|
||||
// A rejected candidate leaves the certified old curve running. In particular,
|
||||
// preserve its acceleration instead of holding one velocity sample.
|
||||
if (!profile.active) return direction * scalar.update(dt);
|
||||
profile.elapsed = std::min(profile.elapsed + dt, profile.duration);
|
||||
velocity = profile.sample(profile.elapsed).first;
|
||||
if (profile.elapsed >= profile.duration) {
|
||||
profile.active = false;
|
||||
const double speed = velocity.norm();
|
||||
scalar.initialize(speed, 0.0);
|
||||
if (speed > EPSILON) direction = velocity / speed;
|
||||
if (speed <= EPSILON) profile.stopping_for_reversal = false;
|
||||
}
|
||||
return velocity;
|
||||
}
|
||||
|
||||
SCurvePlanner::Twist
|
||||
SCurvePlanner::plan(const Twist& target_twist, CartesianFrame frame,
|
||||
double dt, const Eigen::Matrix3d& base_R_tool)
|
||||
{
|
||||
// Smaller periods cannot reliably support command differences in double precision.
|
||||
if (!std::isfinite(dt) || dt < 1e-9) {
|
||||
throw std::invalid_argument("S-curve period must be finite and at least 1e-9 seconds");
|
||||
}
|
||||
if ((frame != CartesianFrame::Base && frame != CartesianFrame::Tool) ||
|
||||
!target_twist.allFinite() ||
|
||||
(frame == CartesianFrame::Tool && !base_R_tool.allFinite())) {
|
||||
throw std::invalid_argument("invalid S-curve target, frame or tool rotation");
|
||||
}
|
||||
Twist target_base = target_twist;
|
||||
if (frame == CartesianFrame::Tool) {
|
||||
target_base.head<3>() = base_R_tool * target_twist.head<3>();
|
||||
target_base.tail<3>() = base_R_tool * target_twist.tail<3>();
|
||||
}
|
||||
if (!target_base.allFinite() || !std::isfinite(target_base.head<3>().norm()) ||
|
||||
!std::isfinite(target_base.tail<3>().norm())) {
|
||||
throw std::invalid_argument("S-curve target magnitude must be finite");
|
||||
}
|
||||
auto staged = *this;
|
||||
staged.twist_base_.head<3>() = planVelocity(staged.linear_velocity_,
|
||||
staged.linear_direction_profile_, staged.current_linear_dir_base_,
|
||||
target_base.head<3>(), dt, continuous_linear_reversal_);
|
||||
staged.twist_base_.tail<3>() = planVelocity(staged.angular_velocity_,
|
||||
staged.angular_direction_profile_, staged.current_angular_dir_base_,
|
||||
target_base.tail<3>(), dt, false);
|
||||
// Keep the public diagnostics based on actual output commands.
|
||||
staged.acceleration_base_ = (staged.twist_base_ - twist_base_) / dt;
|
||||
// Acceleration samples are averages over intervals, located at their centers.
|
||||
staged.jerk_base_ = (staged.acceleration_base_ - acceleration_base_) /
|
||||
(0.5 * previous_period_ + 0.5 * dt);
|
||||
staged.previous_period_ = dt;
|
||||
if (!staged.twist_base_.allFinite() || !staged.acceleration_base_.allFinite() ||
|
||||
!staged.jerk_base_.allFinite()) {
|
||||
throw std::runtime_error("S-curve produced a non-finite command");
|
||||
}
|
||||
*this = std::move(staged);
|
||||
return twist_base_;
|
||||
}
|
||||
|
||||
bool SCurvePlanner::isMoving() const
|
||||
{
|
||||
return linear_direction_profile_.active || angular_direction_profile_.active ||
|
||||
linear_velocity_.isMoving() || angular_velocity_.isMoving();
|
||||
}
|
||||
|
||||
} // namespace cmvr
|
||||
@ -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 = SCurvePlanner::Twist;
|
||||
constexpr double dt = .001;
|
||||
Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; }
|
||||
struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; };
|
||||
Motion reverse(bool continuous, int approach_ticks) {
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(.55, 5, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
planner.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero());
|
||||
for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
planner.setLinearConstraints(.55, 3, 10);
|
||||
Motion result;
|
||||
double position = 0;
|
||||
for (int i = 1; i <= 1500; ++i) {
|
||||
const auto v = planner.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
position += v.y() * dt;
|
||||
result.peak = std::max(result.peak, position);
|
||||
if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt;
|
||||
if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt;
|
||||
if (continuous) {
|
||||
EXPECT_LE(planner.getAccelerationBase().norm(), 3.0 + 1e-7);
|
||||
EXPECT_LE(planner.getJerkBase().norm(), 10.0 + 1e-6);
|
||||
EXPECT_NEAR(v.x(), 0, 1e-12);
|
||||
EXPECT_NEAR(v.z(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
EXPECT_NEAR(planner.getTwistBase().y(), -.08, 1e-9);
|
||||
return result;
|
||||
}
|
||||
TEST(SCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) {
|
||||
for (const int ticks : {0, 80, 120}) {
|
||||
SCOPED_TRACE(ticks);
|
||||
const auto legacy = reverse(false, ticks);
|
||||
const auto continuous = reverse(true, ticks);
|
||||
EXPECT_GT(continuous.reverse_time, 0);
|
||||
EXPECT_LT(continuous.reverse_time, legacy.reverse_time);
|
||||
EXPECT_LT(continuous.return_time, legacy.return_time);
|
||||
EXPECT_LT(continuous.peak, legacy.peak);
|
||||
}
|
||||
}
|
||||
TEST(SCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 1, 4);
|
||||
planner.initialize(y(.02));
|
||||
for (int i = 0; i < 100; ++i) planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR(planner.getTwistBase().y(), 0, 1e-12);
|
||||
EXPECT_TRUE(planner.isMoving());
|
||||
EXPECT_LT(planner.getAccelerationBase().y(), -.39);
|
||||
EXPECT_LT(planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003);
|
||||
}
|
||||
TEST(SCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) {
|
||||
for (double v : {.08, -.08}) {
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
planner.initialize(y(v));
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
EXPECT_GE(planner.plan(Twist::Zero(), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
|
||||
}
|
||||
EXPECT_FALSE(planner.isMoving());
|
||||
EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12);
|
||||
}
|
||||
}
|
||||
TEST(SCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) {
|
||||
for (bool continuous : {true, false}) {
|
||||
for (int offset : {0, 3}) {
|
||||
for (bool accelerating : {false, true}) {
|
||||
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
|
||||
<< " angular=" << (offset == 3) << " accelerating=" << accelerating);
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
planner.setAngularConstraints(1, 3, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
Twist initial = Twist::Zero(), target = Twist::Zero();
|
||||
initial[offset + 1] = .08;
|
||||
target[offset] = .08;
|
||||
if (accelerating) {
|
||||
planner.initialize();
|
||||
planner.plan(initial, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
ASSERT_LT(planner.getTwistBase().norm(), 1e-3);
|
||||
ASSERT_GT(planner.getAccelerationBase().norm(), 1e-3);
|
||||
} else {
|
||||
planner.initialize(initial);
|
||||
}
|
||||
double max_acceleration = 0, max_jerk = 0;
|
||||
Twist previous = planner.getTwistBase();
|
||||
Twist previous_acceleration = planner.getAccelerationBase();
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const auto v = planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const Twist acceleration = (v - previous) / dt;
|
||||
const Twist jerk = (acceleration - previous_acceleration) / dt;
|
||||
EXPECT_LE(acceleration.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(jerk.norm(), 10 + 1e-5);
|
||||
previous = v;
|
||||
previous_acceleration = acceleration;
|
||||
max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm());
|
||||
max_jerk = std::max(max_jerk, planner.getJerkBase().norm());
|
||||
}
|
||||
EXPECT_LE(max_acceleration, 3 + 1e-6);
|
||||
EXPECT_LE(max_jerk, 10 + 1e-6);
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
|
||||
// Same-axis magnitude planning must keep moving when the target
|
||||
// has the same direction, including legacy linear streaming.
|
||||
target *= 1.5;
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
EXPECT_GE(planner.plan(target, CartesianFrame::Base, dt,
|
||||
Eigen::Matrix3d::Identity())[offset], .08 - 1e-9);
|
||||
}
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
|
||||
if (offset == 3) {
|
||||
target = -target;
|
||||
max_acceleration = max_jerk = 0;
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm());
|
||||
max_jerk = std::max(max_jerk, planner.getJerkBase().norm());
|
||||
}
|
||||
EXPECT_LE(max_acceleration, 3 + 1e-6);
|
||||
EXPECT_LE(max_jerk, 10 + 1e-6);
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) {
|
||||
for (bool continuous : {true, false}) {
|
||||
for (int offset : {0, 3}) {
|
||||
for (double max_velocity : {.08, 1.}) {
|
||||
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
|
||||
<< " angular=" << (offset == 3) << " vmax=" << max_velocity);
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(max_velocity, 3, 10);
|
||||
planner.setAngularConstraints(max_velocity, 3, 10);
|
||||
planner.setContinuousLinearReversal(continuous);
|
||||
Twist target = Twist::Zero();
|
||||
target[offset] = .08;
|
||||
planner.initialize(target);
|
||||
Twist previous = target, previous_acceleration = Twist::Zero();
|
||||
double min_speed = .08;
|
||||
for (int i = 0; i < 3000; ++i) {
|
||||
// First reproduce the .01-rad step, then keep rotating the Tool.
|
||||
const double angle = .01 + .2 * i * dt;
|
||||
Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity();
|
||||
rotation(0, 0) = rotation(1, 1) = std::cos(angle);
|
||||
rotation(0, 1) = -std::sin(angle);
|
||||
rotation(1, 0) = std::sin(angle);
|
||||
const Twist v = planner.plan(target, CartesianFrame::Tool, dt, rotation);
|
||||
const Twist a = (v - previous) / dt;
|
||||
const Twist j = (a - previous_acceleration) / dt;
|
||||
EXPECT_LE(v.norm(), max_velocity + 1e-9);
|
||||
EXPECT_LE(a.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(j.norm(), 10 + 1e-5);
|
||||
min_speed = std::min(min_speed, v.norm());
|
||||
previous = v;
|
||||
previous_acceleration = a;
|
||||
}
|
||||
EXPECT_GT(min_speed, .072);
|
||||
for (int i = 0; i < 1500; ++i) {
|
||||
const Twist v = planner.plan(Twist::Zero(), CartesianFrame::Base, dt,
|
||||
Eigen::Matrix3d::Identity());
|
||||
const Twist a = (v - previous) / dt;
|
||||
EXPECT_LE(a.norm(), 3 + 1e-6);
|
||||
EXPECT_LE(((a - previous_acceleration) / dt).norm(), 10 + 1e-5);
|
||||
previous = v;
|
||||
previous_acceleration = a;
|
||||
}
|
||||
EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-10);
|
||||
EXPECT_FALSE(planner.isMoving());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
|
||||
for (const int reverse_ticks : {150, 250, 500}) {
|
||||
SCOPED_TRACE(reverse_ticks);
|
||||
SCurvePlanner reference;
|
||||
reference.setLinearConstraints(1, 3, 10);
|
||||
reference.initialize(y(.08));
|
||||
for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
ASSERT_LT(reference.getTwistBase().y(), 0);
|
||||
auto streaming = reference;
|
||||
streaming.setContinuousLinearReversal(false);
|
||||
EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12);
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
const auto expected = reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const auto actual = streaming.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR((actual - expected).norm(), 0, 1e-9);
|
||||
EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) {
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, .01);
|
||||
planner.initialize(y(.08));
|
||||
Twist target = Twist::Zero();
|
||||
target.x() = .08 * std::sin(1e-4);
|
||||
target.y() = .08 * std::cos(1e-4);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_LE(planner.getAccelerationBase().norm(), 3 + 1e-7);
|
||||
EXPECT_LE(planner.getJerkBase().norm(), .01 + 1e-7);
|
||||
}
|
||||
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-10);
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) {
|
||||
SCurvePlanner planner;
|
||||
planner.setLinearConstraints(1, 3, 10);
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const double period = i % 2 ? .0005 : .001;
|
||||
planner.plan(y(.08), CartesianFrame::Base, period, Eigen::Matrix3d::Identity());
|
||||
EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) {
|
||||
SCurvePlanner actual;
|
||||
actual.setLinearConstraints(.05, 1e-6, .001);
|
||||
actual.initialize(y(.0499995));
|
||||
actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
auto reference = actual;
|
||||
// Removing the small acceleration with this jerk would exceed vmax.
|
||||
// A numerical "near zero" test must not accept and freeze this state.
|
||||
EXPECT_THROW(actual.setLinearConstraints(.05, 1e-6, 1e-8), std::runtime_error);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const Twist a = actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const Twist b = reference.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_DOUBLE_EQ((a - b).norm(), 0);
|
||||
EXPECT_LE(actual.getJerkBase().norm(), .001 + 1e-7);
|
||||
}
|
||||
EXPECT_NEAR(actual.getTwistBase().y(), .05, 1e-12);
|
||||
}
|
||||
|
||||
TEST(SCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) {
|
||||
SCurvePlanner seed;
|
||||
seed.setLinearConstraints(1, 3, 10);
|
||||
seed.setAngularConstraints(1, 3, 10);
|
||||
Twist target = y(.08);
|
||||
target[5] = .12;
|
||||
for (int i = 0; i < 80; ++i)
|
||||
seed.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
|
||||
const auto expect_unchanged = [&](auto operation) {
|
||||
auto expected = seed;
|
||||
auto actual = seed;
|
||||
EXPECT_THROW(operation(actual), std::invalid_argument);
|
||||
const auto compare_state = [&] {
|
||||
EXPECT_DOUBLE_EQ((actual.getTwistBase() - expected.getTwistBase()).norm(), 0);
|
||||
EXPECT_DOUBLE_EQ((actual.getAccelerationBase() - expected.getAccelerationBase()).norm(), 0);
|
||||
EXPECT_DOUBLE_EQ((actual.getJerkBase() - expected.getJerkBase()).norm(), 0);
|
||||
EXPECT_EQ(actual.isMoving(), expected.isMoving());
|
||||
EXPECT_EQ(actual.continuousLinearReversalEnabled(), expected.continuousLinearReversalEnabled());
|
||||
};
|
||||
compare_state();
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
const auto expected_twist = expected.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
const auto actual_twist = actual.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
|
||||
EXPECT_DOUBLE_EQ((actual_twist - expected_twist).norm(), 0);
|
||||
compare_state();
|
||||
}
|
||||
};
|
||||
const double nan = std::numeric_limits<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, CartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); });
|
||||
if (invalid != 0) {
|
||||
expect_unchanged([&](auto& p) { p.setLinearTargetReplanThreshold(invalid); });
|
||||
expect_unchanged([&](auto& p) { p.setAngularTargetReplanThreshold(invalid); });
|
||||
}
|
||||
}
|
||||
for (double invalid : {nan, inf}) {
|
||||
for (int index : {0, 5}) {
|
||||
Twist invalid_twist = target;
|
||||
invalid_twist[index] = invalid;
|
||||
expect_unchanged([&](auto& p) { p.initialize(invalid_twist); });
|
||||
expect_unchanged([&](auto& p) { p.plan(invalid_twist, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); });
|
||||
}
|
||||
Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity();
|
||||
invalid_rotation(1, 2) = invalid;
|
||||
expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Tool, dt, invalid_rotation); });
|
||||
}
|
||||
// Over-limit initialization must not clamp only the internal scalar or
|
||||
// reset linear motion before discovering an invalid angular component.
|
||||
for (int index : {0, 5}) {
|
||||
Twist initial = y(.2);
|
||||
initial[index] = 2;
|
||||
expect_unchanged([&](auto& p) { p.initialize(initial); });
|
||||
}
|
||||
expect_unchanged([&](auto& p) { p.setLinearConstraints(.001, 3, 10); });
|
||||
expect_unchanged([&](auto& p) { p.setLinearConstraints(1, .01, 10); });
|
||||
expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); });
|
||||
expect_unchanged([&](auto& p) { p.plan(target, static_cast<CartesianFrame>(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
|
||||
@ -1,5 +1,4 @@
|
||||
#ifndef CMVR_ES_JOINT_MOTION_PLANNER_H
|
||||
#define CMVR_ES_JOINT_MOTION_PLANNER_H
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@ -10,46 +9,24 @@
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class JointMotionPlanner {
|
||||
public:
|
||||
virtual ~JointMotionPlanner() = default;
|
||||
|
||||
virtual bool init() = 0;
|
||||
|
||||
virtual bool planMoveJ(const std::vector<double>& start,
|
||||
const JointPositionCommand& target,
|
||||
const MotionOptions& options,
|
||||
double speed_scaling,
|
||||
JointTrajectory& trajectory) = 0;
|
||||
|
||||
virtual bool planReplay(const std::vector<double>& current_position,
|
||||
const JointTrajectory& recorded_trajectory,
|
||||
const MotionOptions& options,
|
||||
JointTrajectory& replay_trajectory) = 0;
|
||||
|
||||
bool validateJointTrajectory(const JointTrajectory& trajectory,
|
||||
std::size_t expected_dof,
|
||||
const MotionOptions& limits) const;
|
||||
};
|
||||
|
||||
inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
inline bool validateJointTrajectory(
|
||||
const JointTrajectory& trajectory,
|
||||
const std::size_t expected_dof,
|
||||
const MotionOptions& limits) const
|
||||
const MotionOptions& limits)
|
||||
{
|
||||
if (trajectory.size() < 2 || expected_dof == 0) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory must contain at least "
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory must contain at least "
|
||||
"two points and have a non-zero DOF";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(limits.velocity) || limits.velocity <= 0.0 ||
|
||||
!std::isfinite(limits.acceleration) || limits.acceleration <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity or acceleration limit is invalid";
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity or acceleration limit is invalid";
|
||||
return false;
|
||||
}
|
||||
if (!limits.joint_velocity_limits.empty() &&
|
||||
limits.joint_velocity_limits.size() != expected_dof) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] joint velocity limit count does not match DOF";
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] joint velocity limit count does not match DOF";
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -68,7 +45,7 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
if (!std::isfinite(point.time_s) ||
|
||||
point.position.size() != expected_dof ||
|
||||
point.velocity.size() != expected_dof) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid trajectory point at index=" << i;
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid trajectory point at index=" << i;
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -76,7 +53,7 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
if (i > 0) {
|
||||
dt = point.time_s - trajectory[i - 1].time_s;
|
||||
if (!std::isfinite(dt) || dt <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory time is not increasing at index="
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory time is not increasing at index="
|
||||
<< i;
|
||||
return false;
|
||||
}
|
||||
@ -85,7 +62,7 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
for (std::size_t joint = 0; joint < expected_dof; ++joint) {
|
||||
if (!std::isfinite(point.position[joint]) ||
|
||||
!std::isfinite(point.velocity[joint])) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] non-finite trajectory value at point="
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] non-finite trajectory value at point="
|
||||
<< i << ", joint=" << joint;
|
||||
return false;
|
||||
}
|
||||
@ -95,13 +72,13 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
? limits.velocity
|
||||
: limits.joint_velocity_limits[joint];
|
||||
if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid velocity limit for joint="
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid velocity limit for joint="
|
||||
<< joint;
|
||||
return false;
|
||||
}
|
||||
maximum_velocity = std::max(maximum_velocity, velocity);
|
||||
if (velocity > velocity_limit + kVelocityTolerance) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity limit exceeded at point="
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity limit exceeded at point="
|
||||
<< i << ", joint=" << joint
|
||||
<< ", actual=" << velocity
|
||||
<< ", limit=" << velocity_limit;
|
||||
@ -119,20 +96,22 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
maximum_acceleration, std::abs(acceleration));
|
||||
if (std::abs(acceleration) >
|
||||
limits.acceleration + kAccelerationTolerance) {
|
||||
CMVR_LOG(ERROR) << "[JointMotionPlanner] acceleration limit exceeded at point="
|
||||
CMVR_LOG(ERROR) << "[JointTrajectoryValidation] acceleration limit exceeded at point="
|
||||
<< i << ", joint=" << joint
|
||||
<< ", actual=" << std::abs(acceleration)
|
||||
<< ", limit=" << limits.acceleration;
|
||||
return false;
|
||||
}
|
||||
if (i > 1) {
|
||||
// Interval-average derivatives are located at interval midpoints.
|
||||
const double midpoint_dt = 0.5 * (point.time_s - trajectory[i - 2].time_s);
|
||||
maximum_position_acceleration = std::max(
|
||||
maximum_position_acceleration,
|
||||
std::abs(position_velocity -
|
||||
previous_position_velocity[joint]) / dt);
|
||||
previous_position_velocity[joint]) / midpoint_dt);
|
||||
maximum_jerk = std::max(
|
||||
maximum_jerk,
|
||||
std::abs(acceleration - previous_acceleration[joint]) / dt);
|
||||
std::abs(acceleration - previous_acceleration[joint]) / midpoint_dt);
|
||||
}
|
||||
previous_position_velocity[joint] = position_velocity;
|
||||
previous_acceleration[joint] = acceleration;
|
||||
@ -140,7 +119,7 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
}
|
||||
}
|
||||
|
||||
CMVR_LOG(INFO) << "[JointMotionPlanner] trajectory validated"
|
||||
CMVR_LOG(INFO) << "[JointTrajectoryValidation] trajectory validated"
|
||||
<< ", points=" << trajectory.size()
|
||||
<< ", max_velocity_rad_s=" << maximum_velocity
|
||||
<< ", max_discrete_acceleration_rad_s2=" << maximum_acceleration
|
||||
@ -151,6 +130,5 @@ inline bool JointMotionPlanner::validateJointTrajectory(
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_JOINT_MOTION_PLANNER_H
|
||||
} // namespace cmvr::device
|
||||
@ -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() {
|
||||
|
||||
@ -5,7 +5,6 @@
|
||||
|
||||
#include <Eigen/Dense>
|
||||
|
||||
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::common::math {
|
||||
@ -83,12 +82,6 @@ inline device::CartesianVelocity vectorToVelocity(const Eigen::Matrix<double, 6,
|
||||
return {velocity[0], velocity[1], velocity[2], velocity[3], velocity[4], velocity[5]};
|
||||
}
|
||||
|
||||
inline cmvr::CartesianFrame toPlannerFrame(const device::FrameType frame)
|
||||
{
|
||||
return frame == device::FrameType::Tool ? cmvr::CartesianFrame::Tool
|
||||
: cmvr::CartesianFrame::Base;
|
||||
}
|
||||
|
||||
} // namespace cmvr::common::math
|
||||
|
||||
#endif // CMVR_ES_COMMON_MATH_TRANSFORM_MATH_H
|
||||
|
||||
@ -7,6 +7,8 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
enum class ArmErrorCode {
|
||||
@ -72,8 +74,8 @@ struct SpeedLOptions {
|
||||
// Requested linear jerk (m/s^3), capped by the arm's configured maximum.
|
||||
// Unset uses that maximum.
|
||||
std::optional<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,32 +98,6 @@ struct CartesianWrench {
|
||||
double tz{0.0};
|
||||
};
|
||||
|
||||
struct JointLimit {
|
||||
double lower{0.0};
|
||||
double upper{0.0};
|
||||
double max_velocity{0.0};
|
||||
double max_acceleration{0.0};
|
||||
double max_torque{0.0};
|
||||
};
|
||||
|
||||
struct RobotModel {
|
||||
std::string name;
|
||||
std::string manufacturer;
|
||||
std::string serial_number;
|
||||
std::size_t dof{0};
|
||||
std::vector<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;
|
||||
@ -139,6 +115,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>;
|
||||
@ -185,12 +164,21 @@ struct MotionOptions {
|
||||
double velocity{0.0};
|
||||
double acceleration{0.0};
|
||||
double blend_radius{0.0};
|
||||
double jerk{5.0};
|
||||
double jerk{300.0};
|
||||
std::vector<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 {
|
||||
|
||||
@ -57,6 +57,25 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
@ -66,12 +85,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -116,9 +129,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
@ -217,12 +238,23 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
move_j {
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
|
||||
@ -268,9 +300,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
|
||||
@ -56,6 +56,26 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/gen2/collision/robot_collision.urdf"
|
||||
ignored_pairs { first: "arm_link_5_2" second: "arm_link_7_2" }
|
||||
ignored_pairs { first: "body_link" second: "arm_link_2_2" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
@ -65,12 +85,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -115,9 +129,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
|
||||
@ -57,7 +57,28 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# 轨迹关节位置限位检查的数值容差,单位 rad;0 表示严格检查。
|
||||
joint_limit_tolerance_rad: 0.00001
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
@ -66,12 +87,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -116,9 +131,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
|
||||
@ -58,6 +58,25 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
@ -67,12 +86,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -111,15 +124,23 @@ arm {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 2.0
|
||||
linear_acceleration_max: 15.0
|
||||
linear_jerk_max: 60.0
|
||||
linear_jerk_max: 500.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.005
|
||||
|
||||
@ -58,6 +58,25 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
@ -67,12 +86,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -111,15 +124,23 @@ arm {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.8
|
||||
linear_acceleration_max: 10.0
|
||||
linear_jerk_max: 60.0
|
||||
linear_jerk_max: 200.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
|
||||
@ -57,6 +57,25 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
@ -66,12 +85,6 @@ arm {
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
@ -116,9 +129,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
@ -217,12 +238,23 @@ arm {
|
||||
}
|
||||
|
||||
motion {
|
||||
move_j {
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
|
||||
@ -268,9 +300,17 @@ arm {
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
|
||||
54
cmvr-es/config/devices/motor/tchl_motors.pb.txt
Normal file
54
cmvr-es/config/devices/motor/tchl_motors.pb.txt
Normal file
@ -0,0 +1,54 @@
|
||||
# 同川 TC600E TR 单轴模板;未注册为活动设备。
|
||||
# 当前按实机 PrD.00=0、电子齿轮1:1配置;减速比需读取实机3D06后填写。
|
||||
motor {
|
||||
id: "tchl_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "tchl_single_axis"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_TCHL
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
}
|
||||
|
||||
# 必须先填写实际行程及速度/加速度上限,再设 enable: true;0不是可运行值。
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "TCHL_AXIS_1" q_lb: -3.14 q_ub: 3.14 qd: 10 qdd: 100 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors {
|
||||
id: 1
|
||||
joint_name: "TCHL_AXIS_1"
|
||||
encoder_counts_per_rev: 131072
|
||||
gear_ratio: 101
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -6,42 +6,42 @@ device_manager {
|
||||
id: "mujoco_world"
|
||||
type: DEVICE_TYPE_MUJOCO_WORLD
|
||||
config_file: "devices/mujoco/right_arm_eye_to_hand_world.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_arm_mujoco_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/arm_mujoco_qp.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_viewer"
|
||||
type: DEVICE_TYPE_MUJOCO_VIEWER
|
||||
config_file: "devices/mujoco/mujoco_viewer.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_hand_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_external_touch_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -77,7 +77,7 @@ device_manager {
|
||||
id: "mujoco_zero_touch_dexhand"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
|
||||
@ -4,7 +4,7 @@ task_manager {
|
||||
type: TASK_TYPE_TOUCH_SCREEN
|
||||
run_mode: TASK_RUN_MODE_PERIODIC_STEP
|
||||
control_period_s: 0.001
|
||||
config_file: "tasks/touch_screen_task/touch_screen_task.pb.txt"
|
||||
config_file: "tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
tasks {
|
||||
@ -27,6 +27,6 @@ task_manager {
|
||||
type: TASK_TYPE_QUIC_EDGE
|
||||
run_mode: TASK_RUN_MODE_BLOCKING_SERVICE
|
||||
config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,8 +14,11 @@ touch_screen_task {
|
||||
}
|
||||
|
||||
initialization {
|
||||
# 开始前使用 MoveJ 回到初始关节位置。
|
||||
before_start: false
|
||||
# 正常完成后使用 MoveP 回到初始关节位置。
|
||||
after_finish: true
|
||||
after_failure: true
|
||||
joint_positions { joint_name: "R_SHOULDER_P" rad: -0.338732 }
|
||||
joint_positions { joint_name: "R_SHOULDER_R" rad: 1.265943 }
|
||||
joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.572396 }
|
||||
@ -25,9 +28,9 @@ touch_screen_task {
|
||||
joint_positions { joint_name: "R_WRIST_R" rad: 0.1347 }
|
||||
velocity: 1.0
|
||||
acceleration: 2.0
|
||||
# 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。
|
||||
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
|
||||
skip_position_tolerance_rad: 0.01
|
||||
# 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。
|
||||
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
|
||||
skip_velocity_tolerance_rad_s: 0.1
|
||||
}
|
||||
|
||||
@ -88,15 +91,15 @@ touch_screen_task {
|
||||
stable_frames: 2
|
||||
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
|
||||
timeout_s: 20.0
|
||||
# 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。
|
||||
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
|
||||
pause_when_reached: false
|
||||
}
|
||||
|
||||
touch {
|
||||
speed_l {
|
||||
twist_tool { x: 0.0 y: -0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 5.0
|
||||
linear_jerk: 10.0
|
||||
linear_jerk: 50.0
|
||||
max_distance_m: 0.03
|
||||
}
|
||||
tactile {
|
||||
@ -109,9 +112,9 @@ touch_screen_task {
|
||||
}
|
||||
|
||||
retract {
|
||||
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
twist_tool { x: 0.0 y: 0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 8.0
|
||||
linear_jerk: 40.0 # m/s^3,约束接触后的减速和连续换向。
|
||||
linear_jerk: 100.0 # m/s^3,约束接触后的减速和连续换向。
|
||||
# TCP 后退目标距离,单位为米。
|
||||
distance_m: 0.01
|
||||
}
|
||||
|
||||
@ -14,8 +14,11 @@ touch_screen_task {
|
||||
}
|
||||
|
||||
initialization {
|
||||
# 开始前使用 MoveJ 回到初始关节位置。
|
||||
before_start: true
|
||||
# 正常完成后使用 MoveP 回到初始关节位置。
|
||||
after_finish: true
|
||||
after_failure: true
|
||||
joint_positions { joint_name: "R_SHOULDER_P" rad: -0.2423 }
|
||||
joint_positions { joint_name: "R_SHOULDER_R" rad: 1.2929 }
|
||||
joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.61 }
|
||||
@ -25,9 +28,9 @@ touch_screen_task {
|
||||
joint_positions { joint_name: "R_WRIST_R" rad: -0.08 }
|
||||
velocity: 2.0
|
||||
acceleration: 3.0
|
||||
# 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。
|
||||
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
|
||||
skip_position_tolerance_rad: 0.001
|
||||
# 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。
|
||||
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
|
||||
skip_velocity_tolerance_rad_s: 0.01
|
||||
}
|
||||
|
||||
@ -51,6 +54,17 @@ touch_screen_task {
|
||||
}
|
||||
}
|
||||
|
||||
approach {
|
||||
# MoveP 复用 alignment.target,position_offset_G 表达在屏幕 G 坐标系。
|
||||
enable: true
|
||||
velocity: 0.65 # rad/s
|
||||
acceleration: 1.7 # rad/s^2
|
||||
jerk: 30.0 # rad/s^3
|
||||
timeout_s: 10.0
|
||||
# TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。
|
||||
minimum_clearance_m: 0.01
|
||||
}
|
||||
|
||||
alignment {
|
||||
calibration {
|
||||
# TCP P 相对于屏幕 Hand Tag H 的目标姿态
|
||||
@ -97,15 +111,15 @@ touch_screen_task {
|
||||
stable_frames: 5
|
||||
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
|
||||
timeout_s: 20.0
|
||||
# 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。
|
||||
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
|
||||
pause_when_reached: false
|
||||
}
|
||||
|
||||
touch {
|
||||
speed_l {
|
||||
twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 6.0
|
||||
linear_jerk: 60.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。
|
||||
twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 10.0
|
||||
linear_jerk: 100.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。
|
||||
max_distance_m: 0.02
|
||||
}
|
||||
tactile {
|
||||
@ -118,10 +132,10 @@ touch_screen_task {
|
||||
}
|
||||
|
||||
retract {
|
||||
twist_tool { x: 0.0 y: 0.06 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 4.0
|
||||
linear_jerk: 60.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。
|
||||
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 10.0
|
||||
linear_jerk: 500.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。
|
||||
# TCP 后退目标距离,单位为米。
|
||||
distance_m: 0.05
|
||||
distance_m: 0.02
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user