moveit2
The MoveIt Motion Planning Framework for ROS 2.
trajectory_generator_circ.cpp
Go to the documentation of this file.
1 /*********************************************************************
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2018 Pilz GmbH & Co. KG
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  * copyright notice, this list of conditions and the following
15  * disclaimer in the documentation and/or other materials provided
16  * with the distribution.
17  * * Neither the name of Pilz GmbH & Co. KG nor the names of its
18  * contributors may be used to endorse or promote products derived
19  * from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *********************************************************************/
34 
37 
38 #include <cassert>
39 #include <sstream>
40 
41 #include <kdl/rotational_interpolation_sa.hpp>
42 #include <kdl/trajectory_segment.hpp>
43 #include <kdl/utilities/error.h>
44 #include <kdl/utilities/utility.h>
46 #include <tf2_eigen_kdl/tf2_eigen_kdl.hpp>
47 #include <rclcpp/logger.hpp>
48 #include <rclcpp/logging.hpp>
49 #include <tf2_eigen/tf2_eigen.hpp>
50 #include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
51 
53 {
54 static const rclcpp::Logger LOGGER =
55  rclcpp::get_logger("moveit.pilz_industrial_motion_planner.trajectory_generator_circ");
56 TrajectoryGeneratorCIRC::TrajectoryGeneratorCIRC(const moveit::core::RobotModelConstPtr& robot_model,
57  const LimitsContainer& planner_limits,
58  const std::string& /*group_name*/)
59  : TrajectoryGenerator::TrajectoryGenerator(robot_model, planner_limits)
60 {
62  {
63  throw TrajectoryGeneratorInvalidLimitsException(
64  "Cartesian limits are not fully set for CIRC trajectory generator.");
65  }
66 }
67 
68 void TrajectoryGeneratorCIRC::cmdSpecificRequestValidation(const planning_interface::MotionPlanRequest& req) const
69 {
70  if (!(req.path_constraints.name == "interim" || req.path_constraints.name == "center"))
71  {
72  std::ostringstream os;
73  os << "No path constraint named \"interim\" or \"center\" found (found "
74  "unknown constraint: "
75  << "\"req.path_constraints.name\""
76  << " instead)";
77  throw UnknownPathConstraintName(os.str());
78  }
79 
80  if (req.path_constraints.position_constraints.size() != 1)
81  {
82  throw NoPositionConstraints("CIRC trajectory generator needs valid a position constraint");
83  }
84 
85  if (req.path_constraints.position_constraints.front().constraint_region.primitive_poses.size() != 1)
86  {
87  throw NoPrimitivePose("CIRC trajectory generator needs valid a primitive pose");
88  }
89 }
90 
91 void TrajectoryGeneratorCIRC::extractMotionPlanInfo(const planning_scene::PlanningSceneConstPtr& scene,
93  TrajectoryGenerator::MotionPlanInfo& info) const
94 {
95  RCLCPP_DEBUG(LOGGER, "Extract necessary information from motion plan request.");
96 
97  info.group_name = req.group_name;
98  std::string frame_id{ robot_model_->getModelFrame() };
99 
100  // goal given in joint space
101  if (!req.goal_constraints.front().joint_constraints.empty())
102  {
103  // TODO: link name from goal constraint and path constraint
104  info.link_name = req.path_constraints.position_constraints.front().link_name;
105  if (!robot_model_->hasLinkModel(info.link_name))
106  {
107  throw UnknownLinkNameOfAuxiliaryPoint("Unknown link name of CIRC auxiliary point");
108  }
109 
110  if (req.goal_constraints.front().joint_constraints.size() !=
111  robot_model_->getJointModelGroup(req.group_name)->getActiveJointModelNames().size())
112  {
113  std::ostringstream os;
114  os << "Number of joint constraint = " << req.goal_constraints.front().joint_constraints.size()
115  << " not equal to active joints of group = "
116  << robot_model_->getJointModelGroup(req.group_name)->getActiveJointModelNames().size();
117  throw NumberOfConstraintsMismatch(os.str());
118  }
119 
120  for (const auto& joint_item : req.goal_constraints.front().joint_constraints)
121  {
122  info.goal_joint_position[joint_item.joint_name] = joint_item.position;
123  }
124 
125  computeLinkFK(scene, info.link_name, info.goal_joint_position, info.goal_pose);
126  }
127  // goal given in Cartesian space
128  else
129  {
130  info.link_name = req.goal_constraints.front().position_constraints.front().link_name;
131  if (req.goal_constraints.front().position_constraints.front().header.frame_id.empty() ||
132  req.goal_constraints.front().orientation_constraints.front().header.frame_id.empty())
133  {
134  RCLCPP_WARN(LOGGER, "Frame id is not set in position/orientation constraints of "
135  "goal. Use model frame as default");
136  frame_id = robot_model_->getModelFrame();
137  }
138  else
139  {
140  frame_id = req.goal_constraints.front().position_constraints.front().header.frame_id;
141  }
142  info.goal_pose = getConstraintPose(req.goal_constraints.front());
143  }
144 
145  assert(req.start_state.joint_state.name.size() == req.start_state.joint_state.position.size());
146  for (const auto& joint_name : robot_model_->getJointModelGroup(req.group_name)->getActiveJointModelNames())
147  {
148  auto it{ std::find(req.start_state.joint_state.name.cbegin(), req.start_state.joint_state.name.cend(), joint_name) };
149  if (it == req.start_state.joint_state.name.cend())
150  {
151  std::ostringstream os;
152  os << "Could not find joint \"" << joint_name << "\" of group \"" << req.group_name
153  << "\" in start state of request";
154  throw CircJointMissingInStartState(os.str());
155  }
156  size_t index = it - req.start_state.joint_state.name.cbegin();
157  info.start_joint_position[joint_name] = req.start_state.joint_state.position[index];
158  }
159 
160  computeLinkFK(scene, info.link_name, info.start_joint_position, info.start_pose);
161 
162  // check goal pose ik before Cartesian motion plan starts
163  std::map<std::string, double> ik_solution;
164  if (!computePoseIK(scene, info.group_name, info.link_name, info.goal_pose, frame_id, info.start_joint_position,
165  ik_solution))
166  {
167  // LCOV_EXCL_START
168  std::ostringstream os;
169  os << "Failed to compute inverse kinematics for link: " << info.link_name << " of goal pose";
170  throw CircInverseForGoalIncalculable(os.str());
171  // LCOV_EXCL_STOP // not able to trigger here since lots of checks before
172  // are in place
173  }
174  info.circ_path_point.first = req.path_constraints.name;
175  if (!req.goal_constraints.front().position_constraints.empty())
176  {
177  const moveit_msgs::msg::Constraints& goal = req.goal_constraints.front();
178  info.circ_path_point.second =
180  req.path_constraints.position_constraints.front().constraint_region.primitive_poses.front().position,
181  goal.orientation_constraints.front().orientation, goal.position_constraints.front().target_point_offset)
182  .translation();
183  }
184  else
185  {
186  Eigen::Vector3d circ_path_point;
187  tf2::fromMsg(req.path_constraints.position_constraints.front().constraint_region.primitive_poses.front().position,
188  circ_path_point);
189  info.circ_path_point.second = circ_path_point;
190  }
191 }
192 
193 void TrajectoryGeneratorCIRC::plan(const planning_scene::PlanningSceneConstPtr& scene,
194  const planning_interface::MotionPlanRequest& req, const MotionPlanInfo& plan_info,
195  const double& sampling_time, trajectory_msgs::msg::JointTrajectory& joint_trajectory)
196 {
197  std::unique_ptr<KDL::Path> cart_path(setPathCIRC(plan_info));
198  std::unique_ptr<KDL::VelocityProfile> vel_profile(
199  cartesianTrapVelocityProfile(req.max_velocity_scaling_factor, req.max_acceleration_scaling_factor, cart_path));
200 
201  // combine path and velocity profile into Cartesian trajectory
202  // with the third parameter set to false, KDL::Trajectory_Segment does not
203  // take
204  // the ownship of Path and Velocity Profile
205  KDL::Trajectory_Segment cart_trajectory(cart_path.get(), vel_profile.get(), false);
206 
207  moveit_msgs::msg::MoveItErrorCodes error_code;
208  // sample the Cartesian trajectory and compute joint trajectory using inverse
209  // kinematics
210  if (!generateJointTrajectory(scene, planner_limits_.getJointLimitContainer(), cart_trajectory, plan_info.group_name,
211  plan_info.link_name, plan_info.start_joint_position, sampling_time, joint_trajectory,
212  error_code))
213  {
214  throw CircTrajectoryConversionFailure("Failed to generate valid joint trajectory from the Cartesian path",
215  error_code.val);
216  }
217 }
218 
219 std::unique_ptr<KDL::Path> TrajectoryGeneratorCIRC::setPathCIRC(const MotionPlanInfo& info) const
220 {
221  RCLCPP_DEBUG(LOGGER, "Set Cartesian path for CIRC command.");
222 
223  KDL::Frame start_pose, goal_pose;
224  tf2::transformEigenToKDL(info.start_pose, start_pose);
225  tf2::transformEigenToKDL(info.goal_pose, goal_pose);
226 
227  const auto& eigen_path_point = info.circ_path_point.second;
228  const KDL::Vector path_point{ eigen_path_point.x(), eigen_path_point.y(), eigen_path_point.z() };
229 
230  // pass the ratio of translational by rotational velocity as equivalent radius
231  // to get a trajectory with rotational speed, if no (or very little)
232  // translational distance
233  // The KDL::Path implementation chooses the motion with the longer duration
234  // (translation vs. rotation)
235  // and uses eqradius as scaling factor between the distances.
238 
239  try
240  {
241  if (info.circ_path_point.first == "center")
242  {
243  return PathCircleGenerator::circleFromCenter(start_pose, goal_pose, path_point, eqradius);
244  }
245  else // if (info.circ_path_point.first == "interim")
246  {
247  return PathCircleGenerator::circleFromInterim(start_pose, goal_pose, path_point, eqradius);
248  }
249  }
250  catch (KDL::Error_MotionPlanning_Circle_No_Plane& e)
251  {
252  std::ostringstream os;
253  os << "Failed to create path object for circle." << e.Description();
254  throw CircleNoPlane(os.str());
255  }
256  catch (KDL::Error_MotionPlanning_Circle_ToSmall& e)
257  {
258  std::ostringstream os;
259  os << "Failed to create path object for circle." << e.Description();
260  throw CircleToSmall(os.str());
261  }
263  {
264  std::ostringstream os;
265  os << "Failed to create path object for circle." << e.Description();
266  throw CenterPointDifferentRadius(os.str());
267  }
268 
269  return nullptr;
270 }
271 
272 } // namespace pilz_industrial_motion_planner
double getMaxRotationalVelocity() const
Return the maximal rotational velocity [rad/s], 0 if nothing was set.
double getMaxTranslationalVelocity() const
Return the maximal translational velocity [m/s], 0 if nothing was set.
This class combines CartesianLimit and JointLimits into on single class.
bool hasFullCartesianLimits() const
Return if this LimitsContainer has defined cartesian limits.
const JointLimitsContainer & getJointLimitContainer() const
Obtain the Joint Limits from the container.
const CartesianLimit & getCartesianLimits() const
Return the cartesian limits.
static std::unique_ptr< KDL::Path > circleFromCenter(const KDL::Frame &start_pose, const KDL::Frame &goal_pose, const KDL::Vector &center_point, double eqradius)
set the path circle from start, goal and center point
static std::unique_ptr< KDL::Path > circleFromInterim(const KDL::Frame &start_pose, const KDL::Frame &goal_pose, const KDL::Vector &interim_point, double eqradius)
set circle from start, goal and interim point
TrajectoryGeneratorCIRC(const moveit::core::RobotModelConstPtr &robot_model, const pilz_industrial_motion_planner::LimitsContainer &planner_limits, const std::string &group_name)
Constructor of CIRC Trajectory Generator.
const moveit::core::RobotModelConstPtr robot_model_
std::unique_ptr< KDL::VelocityProfile > cartesianTrapVelocityProfile(const double &max_velocity_scaling_factor, const double &max_acceleration_scaling_factor, const std::unique_ptr< KDL::Path > &path) const
build cartesian velocity profile for the path
const pilz_industrial_motion_planner::LimitsContainer planner_limits_
Vec3fX< details::Vec3Data< double > > Vector3d
Definition: fcl_compat.h:89
frame_id
Definition: pick.py:63
scene
Definition: pick.py:52
bool generateJointTrajectory(const planning_scene::PlanningSceneConstPtr &scene, const JointLimitsContainer &joint_limits, const KDL::Trajectory &trajectory, const std::string &group_name, const std::string &link_name, const std::map< std::string, double > &initial_joint_position, const double &sampling_time, trajectory_msgs::msg::JointTrajectory &joint_trajectory, moveit_msgs::msg::MoveItErrorCodes &error_code, bool check_self_collision=false)
Generate joint trajectory from a KDL Cartesian trajectory.
bool computePoseIK(const planning_scene::PlanningSceneConstPtr &scene, const std::string &group_name, const std::string &link_name, const Eigen::Isometry3d &pose, const std::string &frame_id, const std::map< std::string, double > &seed, std::map< std::string, double > &solution, bool check_self_collision=true, const double timeout=0.0)
compute the inverse kinematics of a given pose, also check robot self collision
bool computeLinkFK(const planning_scene::PlanningSceneConstPtr &scene, const std::string &link_name, const std::map< std::string, double > &joint_state, Eigen::Isometry3d &pose)
compute the pose of a link at give robot state
moveit_msgs::msg::MotionPlanRequest MotionPlanRequest
Eigen::Isometry3d getConstraintPose(const geometry_msgs::msg::Point &position, const geometry_msgs::msg::Quaternion &orientation, const geometry_msgs::msg::Vector3 &offset)
Adapt goal pose, defined by position+orientation, to consider offset.