4 #include <moveit/robot_state/conversions.h>
5 #include <moveit_msgs/MoveItErrorCodes.h>
15 #include <trajopt/file_write_callback.hpp>
22 using namespace trajopt;
35 env_ = std::make_shared<tesseract::tesseract_ros::KDLEnv>();
46 RBX_ERROR(
"No manipulator found in KDL environment");
62 env_ = std::make_shared<tesseract::tesseract_ros::KDLEnv>();
64 if (!
robot_->getModelConst()->hasLinkModel(base_link))
66 RBX_ERROR(
"%s does not exist in robot description", base_link);
70 if (!
robot_->getModelConst()->hasLinkModel(tip_link))
72 RBX_ERROR(
"%s does not exist in robot description", tip_link);
77 RBX_INFO(
"Adding manipulator %s from %s to %s",
manip_, base_link, tip_link);
79 TiXmlDocument srdf_doc;
80 srdf_doc.Parse(
robot_->getSRDFString().c_str());
82 auto *group_element =
new TiXmlElement(
"group");
83 group_element->SetAttribute(
"name",
manip_.
c_str());
84 srdf_doc.FirstChildElement(
"robot")->LinkEndChild(group_element);
86 auto *chain_element =
new TiXmlElement(
"chain");
87 chain_element->SetAttribute(
"base_link", base_link.
c_str());
88 chain_element->SetAttribute(
"tip_link", tip_link.
c_str());
89 group_element->LinkEndChild(chain_element);
91 srdf::ModelSharedPtr srdf;
92 srdf.reset(
new srdf::Model());
93 srdf->initXml(*(
robot_->getURDF()), &srdf_doc);
104 RBX_ERROR(
"No manipulator found in KDL environment");
128 if (init_type != InitInfo::Type::GIVEN_TRAJ)
131 RBX_ERROR(
"init type can only be set to GIVEN_TRAJ calling the setInitialTrajectory() function");
146 if (
env_->checkInitialized())
147 return env_->getLinkNames();
149 throw Exception(1,
"KDL environment not initialized with robot links!");
155 return env_->getManipulator(
manip_)->getLinkNames();
157 throw Exception(1,
"There is no loaded manipulator!");
163 return env_->getManipulator(
manip_)->getJointNames();
165 throw Exception(1,
"There is no loaded manipulator!");
176 throw Exception(1,
"There is no loaded manipulator!");
179 const auto &joint_names =
env_->getManipulator(
manip_)->getJointNames();
180 for (
const auto &name : joints)
182 auto it =
std::find(joint_names.begin(), joint_names.end(), name);
183 if (it == joint_names.end())
184 throw Exception(1,
"One of the joints to be fixed does not exist");
200 auto start_state =
robot_->allocState();
202 start_state->update(
true);
205 ref_state_ = std::make_shared<robot_state::RobotState>(*start_state);
208 auto goal_state =
robot_->allocState();
209 if (request.goal_constraints.size() != 1)
211 RBX_ERROR(
"Ambiguous goal, %lu goal goal_constraints exist, returning default goal",
212 request.goal_constraints.size());
213 res.
error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
216 if (request.goal_constraints[0].joint_constraints.empty())
218 RBX_ERROR(
"No joint constraints specified, returning default goal");
219 res.
error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
224 for (
const auto &joint : request.goal_constraints[0].joint_constraints)
225 variable_map[joint.joint_name] = joint.position;
229 goal_state->setVariablePositions(variable_map);
230 goal_state->update(
true);
237 auto result =
plan(
scene, start_state, goal_state);
238 res.
error_code_.val = moveit_msgs::MoveItErrorCodes::FAILURE;
239 if (result.first and result.second)
243 res.
error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
250 const robot_state::RobotStatePtr &start_state,
251 const robot_state::RobotStatePtr &goal_state)
260 auto pci = std::make_shared<ProblemConstructionInfo>(
env_);
283 const robot_state::RobotStatePtr &start_state,
286 if (
init_type_ == InitInfo::Type::JOINT_INTERPOLATED)
288 RBX_ERROR(
"Straight line interpolation can not be done with a goal_pose.");
292 auto begin_it =
env_->getManipulator(
manip_)->getLinkNames().begin();
293 auto end_it =
env_->getManipulator(
manip_)->getLinkNames().end();
294 auto link_it =
std::find(begin_it, end_it, link);
295 if (link_it == end_it)
297 RBX_ERROR(
"Link %s is not part of robot manipulator", link);
302 ref_state_ = std::make_shared<robot_state::RobotState>(*start_state);
311 auto pci = std::make_shared<ProblemConstructionInfo>(
env_);
336 if (
init_type_ == InitInfo::Type::JOINT_INTERPOLATED)
338 RBX_ERROR(
"Straight line interpolation can not be done with a goal_pose.");
342 auto begin_it =
env_->getManipulator(
manip_)->getLinkNames().begin();
343 auto end_it =
env_->getManipulator(
manip_)->getLinkNames().end();
344 auto link_it =
std::find(begin_it, end_it, link);
345 if (link_it == end_it)
347 RBX_ERROR(
"Link %s is not part of robot manipulator", link);
355 auto pci = std::make_shared<ProblemConstructionInfo>(
env_);
380 if (
init_type_ == InitInfo::Type::JOINT_INTERPOLATED)
382 RBX_ERROR(
"Straight line interpolation can not be done with a start_pose or a goal_pose");
386 auto begin_it =
env_->getManipulator(
manip_)->getLinkNames().begin();
387 auto end_it =
env_->getManipulator(
manip_)->getLinkNames().end();
388 auto start_it =
std::find(begin_it, end_it, start_link);
389 auto goal_it =
std::find(begin_it, end_it, goal_link);
390 if ((start_it == end_it) or (goal_it == end_it))
392 RBX_ERROR(
"Given links %s or %s are not part of robot manipulator", start_link, goal_link);
400 auto pci = std::make_shared<ProblemConstructionInfo>(
env_);
422 const robot_state::RobotStatePtr &start_state)
424 throw Exception(1,
"You need to implement virtual method TrajOptPlanner::plan() in your derived class");
438 boost::filesystem::path path(file_path);
439 path /=
"file_output.csv";
450 pci->basic_info.manip =
manip_;
468 auto jv = std::make_shared<JointVelTermInfo>();
471 jv->term_type = TT_COST;
474 jv->name =
"joint_velocity_cost";
475 pci->cost_infos.push_back(jv);
480 auto collision = std::make_shared<CollisionTermInfo>();
481 collision->name =
"collision_cost";
482 collision->term_type = TT_COST;
484 collision->first_step = 0;
489 pci->cost_infos.push_back(collision);
504 start_state->getVariablePositions() + (
int)start_state->getVariableCount());
507 env_->setState(start_state->getVariableNames(), values);
508 pci->basic_info.start_fixed =
true;
515 env_->setState(start_state);
516 pci->basic_info.start_fixed =
true;
522 Eigen::Quaterniond rotation(start_pose.linear());
523 auto pose_constraint = std::make_shared<CartPoseTermInfo>();
524 pose_constraint->term_type = TT_CNT;
525 pose_constraint->link = link;
526 pose_constraint->timestep = 0;
527 pose_constraint->xyz = start_pose.translation();
528 pose_constraint->wxyz = Eigen::Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
531 pose_constraint->name =
"start_pose_cnt_link_" + link;
532 pci->cnt_infos.push_back(pose_constraint);
545 const auto &manip_joint_names =
env_->getManipulator(
manip_)->getJointNames();
558 auto joint_pos_constraint = std::make_shared<JointPosTermInfo>();
559 joint_pos_constraint->term_type = TT_CNT;
560 joint_pos_constraint->name =
"goal_state_cnt";
562 joint_pos_constraint->targets = goal_state;
565 pci->cnt_infos.push_back(joint_pos_constraint);
567 if (
init_type_ == InitInfo::Type::JOINT_INTERPOLATED)
568 pci->init_info.data =
569 Eigen::Map<const Eigen::VectorXd>(goal_state.
data(),
static_cast<long int>(goal_state.
size()));
575 Eigen::Quaterniond rotation(goal_pose.linear());
576 auto pose_constraint = std::make_shared<CartPoseTermInfo>();
577 pose_constraint->term_type = TT_CNT;
578 pose_constraint->link = link;
580 pose_constraint->xyz = goal_pose.translation();
581 pose_constraint->wxyz = Eigen::Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
584 pose_constraint->name =
"goal_pose_cnt_link_" + link;
585 pci->cnt_infos.push_back(pose_constraint);
594 TrajOptProbPtr prob = ConstructProblem(*pci);
595 sco::BasicTrustRegionSQP opt(prob);
612 double total_time = 0.0;
618 auto init_trajectory = prob->GetInitTraj();
623 int cols = pci->kin->numJoints();
626 init_trajectory.block(1, 0, rows, cols) += (Eigen::MatrixXd::Constant(rows, cols, -noise) +
628 (Eigen::MatrixXd::Random(rows, cols) * 0.5 +
629 Eigen::MatrixXd::Constant(rows, cols, 0.5)));
632 opt.initialize(trajToDblVec(init_trajectory));
635 ros::Time tStart = ros::Time::now();
639 double time = (ros::Time::now() - tStart).toSec();
643 if (opt.results().status == sco::OptStatus::OPT_CONVERGED)
646 planner_result.first =
true;
649 auto tss_current_traj = getTraj(opt.x(), prob->GetVars());
651 std::make_shared<robot_trajectory::RobotTrajectory>(
robot_->getModelConst(),
group_);
654 auto const &ct = std::make_shared<Trajectory>(current_traj);
655 bool is_ct_collision_free = ct->isCollisionFree(
scene);
658 if ((opt.results().total_cost < best_cost) and is_ct_collision_free)
661 best_cost = opt.results().total_cost;
671 planner_result.second =
true;
685 RBX_INFO(
"OPTIMIZATION STATUS: %s", sco::statusToString(opt.results().status));
688 RBX_INFO(
"COLLISION STATUS: %s", (planner_result.second) ?
"COLLISION FREE" :
"IN COLLISION");
690 if (planner_result.first)
698 return planner_result;
703 sco::BasicTrustRegionSQPParameters params;
Exception that contains a message and an error code.
A shared pointer wrapper for robowflex::MotionRequestBuilder.
An abstract interface to a motion planning algorithm.
RobotPtr robot_
The robot to plan for.
A shared pointer wrapper for robowflex::Robot.
A const shared pointer wrapper for robowflex::Scene.
const trajopt::TrajArray & getTesseractTrajectory() const
Get the trajectory that resulted in the last call to plan() in Tesseract format.
void addGoalState(const MotionRequestBuilderPtr &request, std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Add a (joint) configuration constraint in the last waypoint taken from request.
trajopt::TrajArray tesseract_trajectory_
std::shared_ptr< std::ofstream > stream_ptr_
Debug file stream.
std::string manip_
Name of manipulator chain to check for collisions.
robot_state::RobotStatePtr ref_state_
Reference state to build moveit trajectory waypoints.
double getPlanningTime() const
Get the time spent by the planner the last time it was called.
const std::vector< std::string > & getManipulatorJoints() const
Get the joint names of the env manipulator.
const std::vector< std::string > & getEnvironmentLinks() const
Get the link names in the tesseract KDL environment.
sco::BasicTrustRegionSQPParameters getTrustRegionSQPParameters() const
Get parameters of the SQP.
double time_
Time taken by the optimizer the last time it was called.
void addCollisionAvoidance(std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Add collision avoidance cost to the trajectory optimization for all waypoints.
struct robowflex::TrajOptPlanner::Options options
void setWriteFile(bool file_write_cb, const std::string &file_path="")
Set whether a report file (for the optimization) should be written or not.
void setInitialTrajectory(const robot_trajectory::RobotTrajectoryPtr &init_trajectory)
Set initial trajectory for TrajOpt and set init_type to GIVEN_TRAJ.
void addGoalPose(const RobotPose &goal_pose, const std::string &link, std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Add a cartesian pose constraint goal_pose for link in the last waypoint.
void addVelocityCost(std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Add velocity cost to the trajectory optimization.
const std::vector< std::string > & getManipulatorLinks() const
Get the link names of the env manipulator.
std::vector< std::string > getPlannerConfigs() const override
Get planner configurations offered by this planner. Any of the configurations returned can be set as ...
bool file_write_cb_
Whether to write a debug file or not.
void problemConstructionInfo(std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Create a TrajOpt problem construction info object with default values.
trajopt::TrajArray initial_trajectory_
Initial trajectory (if any).
void fixJoints(const std::vector< std::string > &joints)
Constrain certain joints during optimization to their initial value.
std::pair< bool, bool > PlannerResult
Planner result: first->converged, second->collision_free.
PlannerResult solve(const SceneConstPtr &scene, const std::shared_ptr< trajopt::ProblemConstructionInfo > &pci)
Solve SQP optimization problem.
trajopt::InitInfo::Type init_type_
robot_trajectory::RobotTrajectoryPtr trajectory_
const robot_trajectory::RobotTrajectoryPtr & getTrajectory() const
Get the trajectory that resulted in the last call to plan().
std::string group_
Name of group to plan for.
std::string file_path_
Path of debug file.
void addStartState(const MotionRequestBuilderPtr &request, std::shared_ptr< trajopt::ProblemConstructionInfo > pci)
Add a (joint) configuration constraint in the first waypoint taken from request.
void addStartPose(const RobotPose &start_pose, const std::string &link, std::shared_ptr< trajopt::ProblemConstructionInfo > pci) const
Add a cartesian pose constraint start_pose for link in the first waypoint.
planning_interface::MotionPlanResponse plan(const SceneConstPtr &scene, const planning_interface::MotionPlanRequest &request) override
Plan a motion given a request and a scene.
bool initialize(const std::string &manip)
Initialize planner. The user must specify a chain group defined in the robot's srdf that contains all...
void setInitType(const trajopt::InitInfo::Type &init_type)
Set type of initialization to use for the trajectory optimization. Current options are: STATIONARY JO...
std::vector< int > fixed_joints_
TrajOptPlanner(const RobotPtr &robot, const std::string &group_name, const std::string &name="trajopt")
Constructor.
tesseract::tesseract_ros::KDLEnvPtr env_
KDL environment.
#define RBX_ERROR(fmt,...)
Output a error logging message.
#define RBX_INFO(fmt,...)
Output a info logging message.
bool robotStateMsgToRobotState(const Transforms &tf, const moveit_msgs::RobotState &robot_state, RobotState &state, bool copy_attached_bodies=true)
moveit_msgs::MotionPlanRequest MotionPlanRequest
Functions for loading and animating robots in Blender.
void manipTesseractTrajToRobotTraj(const tesseract::TrajArray &tesseract_traj, const robot_state::RobotStatePtr &ref_state, const std::string &manip, const tesseract::tesseract_ros::KDLEnvPtr &env, robot_trajectory::RobotTrajectoryPtr trajectory)
Transform a tesseract trajectory to a robot trajectory.
bool sceneToTesseractEnv(const robowflex::SceneConstPtr &scene, tesseract::tesseract_ros::KDLEnvPtr env)
Add scene collision objects to a (previously initialized) KDL environment.
bool addAttachedBodiesToTesseractEnv(const robot_state::RobotStatePtr &state, tesseract::tesseract_ros::KDLEnvPtr env)
Add bodies attached to the robot scratch state to the KDL environment.
void robotTrajToManipTesseractTraj(const robot_trajectory::RobotTrajectoryPtr &robot_traj, const std::string &manip, const tesseract::tesseract_ros::KDLEnvPtr &env, tesseract::TrajArray &trajectory)
Transform a robot_trajectory to a tesseract manipulator trajectory.
void robotStateToManipState(const robot_state::RobotStatePtr &robot_state, const std::vector< std::string > &manip_joint_names, std::vector< double > &manip_joint_values)
Transform a robot_state to a vector representing joint values for the manipulator (in the order given...
Main namespace. Contains all library classes and functions.
std::decay< decltype(std::declval< moveit::core::Transforms >().getTransform("")) >::type RobotPose
A pose (point in SE(3)) used in various functions. Defined from what MoveIt! uses.
Functions for loading and animating scenes in Blender.
moveit_msgs::MoveItErrorCodes error_code_
robot_trajectory::RobotTrajectoryPtr trajectory_
double pose_cnt_rot_coeffs
Coefficients for pose constraints (rotation).
bool use_time
Whether any cost/cnt use time.
bool use_cont_col_avoid
Whether to use continuous collision avoidance or not.
double merit_coeff_increase_ratio
Ratio that we increate coeff each time.
double improve_ratio_threshold
double min_approx_improve
sco::ModelType backend_optimizer
Optimizer to use.
double joint_vel_coeffs
Coefficients for joint_vel costs.
double dt_lower_lim
1/max_dt.
double max_merit_coeff_increases
Number of times that we jack up penalty coefficient.
double joint_pos_cnt_coeffs
Coefficients for joint position constraints.
double default_safety_margin
Default safety margin for collision avoidance.
bool return_after_timeout
double merit_error_coeff
Initial penalty coefficient.
double trust_expand_ratio
double dt_upper_lim
1/min_dt.
double init_info_dt
Value of dt in init_info.
bool start_fixed
Whether to use the current env state as a fixed initial state.
int num_waypoints
Number of waypoints.
double joint_state_safety_margin_coeffs
double min_approx_improve_frac
double trust_box_size
Current size of trust region (component-wise).
double max_iter
The max number of iterations.
double min_trust_box_size
double trust_shrink_ratio
double pose_cnt_pos_coeffs
Coefficients for pose constraints (position).
double default_safety_margin_coeffs
Coefficients for safety margin.