moveit2
The MoveIt Motion Planning Framework for ROS 2.
problem_description.cpp
Go to the documentation of this file.
1 /*********************************************************************
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2013, John Schulman
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 copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  * http://opensource.org/licenses/BSD-2-Clause
32  *********************************************************************/
33 
34 #include <boost/algorithm/string.hpp>
35 
36 #include <ros/ros.h>
37 
40 #include <moveit_msgs/MotionPlanRequest.h>
41 
42 #include <trajopt/trajectory_costs.hpp>
43 #include <trajopt_sco/expr_op_overloads.hpp>
44 #include <trajopt_sco/expr_ops.hpp>
45 #include <trajopt_utils/eigen_slicing.hpp>
46 #include <trajopt_utils/logging.hpp>
47 #include <trajopt_utils/vector_ops.hpp>
48 
51 
59 void checkParameterSize(trajopt::DblVec& parameter, const unsigned int& expected_size, const std::string& name,
60  const bool& apply_first = true)
61 {
62  if (apply_first == true && parameter.size() == 1)
63  {
64  parameter = trajopt::DblVec(expected_size, parameter[0]);
65  ROS_INFO("1 %s given. Applying to all %i joints", name.c_str(), expected_size);
66  }
67  else if (parameter.size() != expected_size)
68  {
69  PRINT_AND_THROW(boost::format("wrong number of %s. expected %i got %i") % name % expected_size % parameter.size());
70  }
71 }
72 
73 namespace trajopt_interface
74 {
76 {
77 }
78 
80  : OptProb(problem_info.basic_info.convex_solver)
81  , planning_scene_(problem_info.planning_scene)
82  , planning_group_(problem_info.planning_group_name)
83 {
84  moveit::core::RobotModelConstPtr robot_model = planning_scene_->getRobotModel();
85  moveit::core::RobotState current_state = planning_scene_->getCurrentState();
86  const moveit::core::JointModelGroup* joint_model_group = current_state.getJointModelGroup(planning_group_);
87 
88  moveit::core::JointBoundsVector bounds = joint_model_group->getActiveJointModelsBounds();
89  dof_ = joint_model_group->getActiveJointModelNames().size(); // or bounds.size();
90 
91  int n_steps = problem_info.basic_info.n_steps;
92 
93  ROS_INFO(" ======================================= problem_description: limits");
94  Eigen::MatrixX2d limits(dof_, 2);
95  for (int k = 0; k < limits.size() / 2; ++k)
96  {
97  moveit::core::JointModel::Bounds bound = *bounds[k];
98  // In MoveIt, joints are considered to have multiple dofs but we only have single dof joints:
99  moveit::core::VariableBounds joint_bound = bound.front();
100 
101  limits(k, 0) = joint_bound.min_position_;
102  limits(k, 1) = joint_bound.max_position_;
103 
104  ROS_INFO("joint %i with lower bound: %f, upper bound: %f", k, joint_bound.min_position_, joint_bound.max_position_);
105  }
106 
107  Eigen::VectorXd lower, upper;
108  lower = limits.col(0);
109  upper = limits.col(1);
110 
111  trajopt::DblVec vlower, vupper;
112  std::vector<std::string> names;
113  for (int i = 0; i < n_steps; ++i)
114  {
115  for (int j = 0; j < dof_; ++j)
116  {
117  names.push_back((boost::format("j_%i_%i") % i % j).str());
118  }
119  vlower.insert(vlower.end(), lower.data(), lower.data() + lower.size());
120  vupper.insert(vupper.end(), upper.data(), upper.data() + upper.size());
121 
122  if (problem_info.basic_info.use_time == true)
123  {
124  vlower.insert(vlower.end(), problem_info.basic_info.dt_lower_lim);
125  vupper.insert(vupper.end(), problem_info.basic_info.dt_upper_lim);
126  names.push_back((boost::format("dt_%i") % i).str());
127  }
128  }
129 
130  sco::VarVector trajvarvec = createVariables(names, vlower, vupper);
131  matrix_traj_vars = trajopt::VarArray(n_steps, dof_ + (problem_info.basic_info.use_time ? 1 : 0), trajvarvec.data());
132  // matrix_traj_vars is essentially a matrix of elements like:
133  // j_0_0, j_0_1 ...
134  // j_1_0, j_1_1 ...
135  // its size is n_steps by n_dof
136 }
137 
138 TrajOptProblemPtr ConstructProblem(const ProblemInfo& pci)
139 {
140  const BasicInfo& bi = pci.basic_info;
141  int n_steps = bi.n_steps;
142 
143  bool use_time = false;
144  // Check that all costs and constraints support the types that are specified in pci
145  for (TermInfoPtr cost : pci.cost_infos)
146  {
147  if (cost->term_type & TT_CNT)
148  ROS_WARN("%s is listed as a type TT_CNT but was added to cost_infos", (cost->name).c_str());
149  if (!(cost->getSupportedTypes() & TT_COST))
150  PRINT_AND_THROW(boost::format("%s is only a constraint, but you listed it as a cost") % cost->name);
151  if (cost->term_type & TT_USE_TIME)
152  {
153  use_time = true;
154  if (!(cost->getSupportedTypes() & TT_USE_TIME))
155  PRINT_AND_THROW(boost::format("%s does not support time, but you listed it as a using time") % cost->name);
156  }
157  }
158  for (TermInfoPtr cnt : pci.cnt_infos)
159  {
160  if (cnt->term_type & TT_COST)
161  ROS_WARN("%s is listed as a type TT_COST but was added to cnt_infos", (cnt->name).c_str());
162  if (!(cnt->getSupportedTypes() & TT_CNT))
163  PRINT_AND_THROW(boost::format("%s is only a cost, but you listed it as a constraint") % cnt->name);
164  if (cnt->term_type & TT_USE_TIME)
165  {
166  use_time = true;
167  if (!(cnt->getSupportedTypes() & TT_USE_TIME))
168  PRINT_AND_THROW(boost::format("%s does not support time, but you listed it as a using time") % cnt->name);
169  }
170  }
171 
172  // Check that if a cost or constraint uses time, basic_info is set accordingly
173  if ((use_time == true) && (pci.basic_info.use_time == false))
174  PRINT_AND_THROW("A term is using time and basic_info is not set correctly. Try basic_info.use_time = true");
175 
176  // This could be removed in the future once we are sure that all costs are
177  if ((use_time == false) && (pci.basic_info.use_time == true))
178  PRINT_AND_THROW("No terms use time and basic_info is not set correctly. Try basic_info.use_time = false");
179 
180  auto prob = std::make_shared<TrajOptProblem>(pci);
181 
182  // Generate initial trajectory and check its size
183  moveit::core::RobotModelConstPtr robot_model = pci.planning_scene->getRobotModel();
184  moveit::core::RobotState current_state = pci.planning_scene->getCurrentState();
185 
186  const moveit::core::JointModelGroup* joint_model_group = current_state.getJointModelGroup(pci.planning_group_name);
187  int n_dof = prob->GetNumDOF();
188 
189  std::vector<double> current_joint_values;
190  current_state.copyJointGroupPositions(joint_model_group, current_joint_values);
191 
192  trajopt::TrajArray init_traj;
193  generateInitialTrajectory(pci, current_joint_values, init_traj);
194 
195  if (pci.basic_info.use_time == true)
196  {
197  prob->SetHasTime(true);
198  if (init_traj.rows() != n_steps || init_traj.cols() != n_dof + 1)
199  {
200  PRINT_AND_THROW(boost::format("Initial trajectory is not the right size matrix\n"
201  "Expected %i rows (time steps) x %i columns (%i dof + 1 time column)\n"
202  "Got %i rows and %i columns") %
203  n_steps % (n_dof + 1) % n_dof % init_traj.rows() % init_traj.cols());
204  }
205  }
206  else
207  {
208  prob->SetHasTime(false);
209  if (init_traj.rows() != n_steps || init_traj.cols() != n_dof)
210  {
211  PRINT_AND_THROW(boost::format("Initial trajectory is not the right size matrix\n"
212  "Expected %i rows (time steps) x %i columns\n"
213  "Got %i rows and %i columns") %
214  n_steps % n_dof % init_traj.rows() % init_traj.cols());
215  }
216  }
217  prob->SetInitTraj(init_traj);
218 
219  trajopt::VarArray matrix_traj_vars_temp;
220  // If start_fixed, constrain the joint values for the first time step to be their initialized values
221  if (bi.start_fixed)
222  {
223  if (init_traj.rows() < 1)
224  {
225  PRINT_AND_THROW("Initial trajectory must contain at least the start state.");
226  }
227 
228  if (init_traj.cols() != (n_dof + (use_time ? 1 : 0)))
229  {
230  PRINT_AND_THROW("robot dof values don't match initialization. I don't "
231  "know what you want me to use for the dof values");
232  }
233 
234  for (int j = 0; j < static_cast<int>(n_dof); ++j)
235  {
236  matrix_traj_vars_temp = prob->GetVars();
237  prob->addLinearConstraint(sco::exprSub(sco::AffExpr(matrix_traj_vars_temp(0, j)), init_traj(0, j)), sco::EQ);
238  }
239  }
240 
241  // Apply constraint to each fixed dof to its initial value for all timesteps (freeze that column)
242  if (!bi.dofs_fixed.empty())
243  {
244  for (const int& dof_ind : bi.dofs_fixed)
245  {
246  for (int i = 1; i < prob->GetNumSteps(); ++i)
247  {
248  matrix_traj_vars_temp = prob->GetVars();
249  prob->addLinearConstraint(sco::exprSub(sco::AffExpr(matrix_traj_vars_temp(i, dof_ind)),
250  sco::AffExpr(init_traj(0, dof_ind))),
251  sco::EQ);
252  }
253  }
254  }
255 
256  for (const TermInfoPtr& ci : pci.cost_infos)
257  {
258  ci->addObjectiveTerms(*prob);
259  }
260 
261  for (const TermInfoPtr& ci : pci.cnt_infos)
262  {
263  ci->addObjectiveTerms(*prob);
264  }
265  return prob;
266 }
267 
269 {
270  pos_coeffs = Eigen::Vector3d::Ones();
271  rot_coeffs = Eigen::Vector3d::Ones();
272  tcp.setIdentity();
273 }
274 
276 {
277  unsigned int n_dof = prob.GetActiveGroupNumDOF();
278 
279  Eigen::Isometry3d input_pose;
280  Eigen::Quaterniond q(wxyz(0), wxyz(1), wxyz(2), wxyz(3));
281  input_pose.linear() = q.matrix();
282  input_pose.translation() = xyz;
283 
284  if (term_type == (TT_COST | TT_USE_TIME))
285  {
286  ROS_ERROR("Use time version of this term has not been defined.");
287  }
288  else if (term_type == (TT_CNT | TT_USE_TIME))
289  {
290  ROS_ERROR("Use time version of this term has not been defined.");
291  }
292  else if ((term_type & TT_COST) && ~(term_type | ~TT_USE_TIME))
293  {
294  sco::VectorOfVectorPtr f = std::make_shared<CartPoseErrCalculator>(input_pose, prob.GetPlanningScene(), link, tcp);
295  prob.addCost(std::make_shared<sco::CostFromErrFunc>(f, prob.GetVarRow(timestep, 0, n_dof),
296  concatVector(rot_coeffs, pos_coeffs), sco::ABS, name));
297  }
298  else if ((term_type & TT_CNT) && ~(term_type | ~TT_USE_TIME))
299  {
300  sco::VectorOfVectorPtr f = std::make_shared<CartPoseErrCalculator>(input_pose, prob.GetPlanningScene(), link, tcp);
301  prob.addConstraint(std::make_shared<sco::ConstraintFromErrFunc>(
302  f, prob.GetVarRow(timestep, 0, n_dof), concatVector(rot_coeffs, pos_coeffs), sco::EQ, name));
303  }
304  else
305  {
306  ROS_WARN("CartPoseTermInfo does not have a valid term_type defined. No cost/constraint applied");
307  }
308 }
309 
311 {
312  unsigned int n_dof = prob.GetActiveGroupNumDOF();
313 
314  // If optional parameter not given, set to default
315  if (coeffs.empty())
316  coeffs = trajopt::DblVec(n_dof, 1);
317  if (upper_tols.empty())
318  upper_tols = trajopt::DblVec(n_dof, 0);
319  if (lower_tols.empty())
320  lower_tols = trajopt::DblVec(n_dof, 0);
321  if (last_step <= -1)
322  last_step = prob.GetNumSteps() - 1;
323 
324  // Check time step is valid
325  if ((prob.GetNumSteps() - 1) <= first_step)
326  first_step = prob.GetNumSteps() - 1;
327  if ((prob.GetNumSteps() - 1) <= last_step)
328  last_step = prob.GetNumSteps() - 1;
329  // if (last_step == first_step)
330  // last_step += 1;
331  if (last_step < first_step)
332  {
333  int tmp = first_step;
335  last_step = tmp;
336  ROS_WARN("Last time step for JointPosTerm comes before first step. Reversing them.");
337  }
338  if (last_step == -1) // last_step not set
340 
341  // Check if parameters are the correct size.
342  checkParameterSize(coeffs, n_dof, "JointPoseTermInfo coeffs", true);
343  checkParameterSize(targets, n_dof, "JointPoseTermInfo targets", true);
344  checkParameterSize(upper_tols, n_dof, "JointPoseTermInfo upper_tols", true);
345  checkParameterSize(lower_tols, n_dof, "JointPoseTermInfo lower_tols", true);
346 
347  // Check if tolerances are all zeros
348  bool is_upper_zeros =
349  std::all_of(upper_tols.begin(), upper_tols.end(), [](double i) { return util::doubleEquals(i, 0.); });
350  bool is_lower_zeros =
351  std::all_of(lower_tols.begin(), lower_tols.end(), [](double i) { return util::doubleEquals(i, 0.); });
352 
353  // Get vars associated with joints
354  trajopt::VarArray vars = prob.GetVars();
355  trajopt::VarArray joint_vars = vars.block(0, 0, vars.rows(), static_cast<int>(n_dof));
356  if (prob.GetHasTime())
357  ROS_INFO("JointPoseTermInfo does not differ based on setting of TT_USE_TIME");
358 
359  if (term_type & TT_COST)
360  {
361  // If the tolerances are 0, an equality cost is set. Otherwise it's a hinged "inequality" cost
362  if (is_upper_zeros && is_lower_zeros)
363  {
364  prob.addCost(std::make_shared<trajopt::JointPosEqCost>(joint_vars, util::toVectorXd(coeffs),
365  util::toVectorXd(targets), first_step, last_step));
366  prob.getCosts().back()->setName(name);
367  }
368  else
369  {
370  prob.addCost(std::make_shared<trajopt::JointPosIneqCost>(joint_vars, util::toVectorXd(coeffs),
371  util::toVectorXd(targets), util::toVectorXd(upper_tols),
372  util::toVectorXd(lower_tols), first_step, last_step));
373  prob.getCosts().back()->setName(name);
374  }
375  }
376  else if (term_type & TT_CNT)
377  {
378  // If the tolerances are 0, an equality cnt is set. Otherwise it's an inequality constraint
379  if (is_upper_zeros && is_lower_zeros)
380  {
381  prob.addConstraint(std::make_shared<trajopt::JointPosEqConstraint>(
382  joint_vars, util::toVectorXd(coeffs), util::toVectorXd(targets), first_step, last_step));
383  prob.getConstraints().back()->setName(name);
384  }
385  else
386  {
387  prob.addConstraint(std::make_shared<trajopt::JointPosIneqConstraint>(
388  joint_vars, util::toVectorXd(coeffs), util::toVectorXd(targets), util::toVectorXd(upper_tols),
389  util::toVectorXd(lower_tols), first_step, last_step));
390  prob.getConstraints().back()->setName(name);
391  }
392  }
393  else
394  {
395  ROS_WARN("JointPosTermInfo does not have a valid term_type defined. No cost/constraint applied");
396  }
397 }
398 
400 {
401  unsigned int n_dof = prob.GetNumDOF();
402 
403  // If optional parameter not given, set to default
404  if (coeffs.empty())
405  coeffs = trajopt::DblVec(n_dof, 1);
406  if (upper_tols.empty())
407  upper_tols = trajopt::DblVec(n_dof, 0);
408  if (lower_tols.empty())
409  lower_tols = trajopt::DblVec(n_dof, 0);
410  if (last_step <= -1)
411  last_step = prob.GetNumSteps() - 1;
412 
413  // If only one time step is desired, calculate velocity with next step (2 steps are needed for 1 velocity calculation)
414  if ((prob.GetNumSteps() - 2) <= first_step)
415  first_step = prob.GetNumSteps() - 2;
416  if ((prob.GetNumSteps() - 1) <= last_step)
417  last_step = prob.GetNumSteps() - 1;
418  if (last_step == first_step)
419  last_step += 1;
420  if (last_step < first_step)
421  {
422  int tmp = first_step;
424  last_step = tmp;
425  ROS_WARN("Last time step for JointVelTerm comes before first step. Reversing them.");
426  }
427 
428  // Check if parameters are the correct size.
429  checkParameterSize(coeffs, n_dof, "JointVelTermInfo coeffs", true);
430  checkParameterSize(targets, n_dof, "JointVelTermInfo targets", true);
431  checkParameterSize(upper_tols, n_dof, "JointVelTermInfo upper_tols", true);
432  checkParameterSize(lower_tols, n_dof, "JointVelTermInfo lower_tols", true);
433  assert(last_step > first_step);
434  assert(first_step >= 0);
435 
436  // Check if tolerances are all zeros
437  bool is_upper_zeros =
438  std::all_of(upper_tols.begin(), upper_tols.end(), [](double i) { return util::doubleEquals(i, 0.); });
439  bool is_lower_zeros =
440  std::all_of(lower_tols.begin(), lower_tols.end(), [](double i) { return util::doubleEquals(i, 0.); });
441 
442  // Get vars associated with joints
443  trajopt::VarArray vars = prob.GetVars();
444  trajopt::VarArray joint_vars = vars.block(0, 0, vars.rows(), static_cast<int>(n_dof));
445 
446  if (term_type == (TT_COST | TT_USE_TIME))
447  {
448  unsigned num_vels = last_step - first_step;
449 
450  // Apply separate cost to each joint b/c that is how the error function is currently written
451  for (size_t j = 0; j < n_dof; ++j)
452  {
453  // Get a vector of a single column of vars
454  sco::VarVector joint_vars_vec = joint_vars.cblock(first_step, j, last_step - first_step + 1);
455  sco::VarVector time_vars_vec = vars.cblock(first_step, vars.cols() - 1, last_step - first_step + 1);
456 
457  // If the tolerances are 0, an equality cost is set
458  if (is_upper_zeros && is_lower_zeros)
459  {
460  trajopt::DblVec single_jnt_coeffs = trajopt::DblVec(num_vels * 2, coeffs[j]);
461  prob.addCost(std::make_shared<sco::CostFromErrFunc>(
462  std::make_shared<JointVelErrCalculator>(targets[j], upper_tols[j], lower_tols[j]),
463  std::make_shared<JointVelJacobianCalculator>(), concatVector(joint_vars_vec, time_vars_vec),
464  util::toVectorXd(single_jnt_coeffs), sco::SQUARED, name + "_j" + std::to_string(j)));
465  }
466  // Otherwise it's a hinged "inequality" cost
467  else
468  {
469  trajopt::DblVec single_jnt_coeffs = trajopt::DblVec(num_vels * 2, coeffs[j]);
470  prob.addCost(std::make_shared<sco::CostFromErrFunc>(
471  std::make_shared<JointVelErrCalculator>(targets[j], upper_tols[j], lower_tols[j]),
472  std::make_shared<JointVelJacobianCalculator>(), concatVector(joint_vars_vec, time_vars_vec),
473  util::toVectorXd(single_jnt_coeffs), sco::HINGE, name + "_j" + std::to_string(j)));
474  }
475  }
476  }
477  else if (term_type == (TT_CNT | TT_USE_TIME))
478  {
479  unsigned num_vels = last_step - first_step;
480 
481  // Apply separate cnt to each joint b/c that is how the error function is currently written
482  for (size_t j = 0; j < n_dof; ++j)
483  {
484  // Get a vector of a single column of vars
485  sco::VarVector joint_vars_vec = joint_vars.cblock(first_step, j, last_step - first_step + 1);
486  sco::VarVector time_vars_vec = vars.cblock(first_step, vars.cols() - 1, last_step - first_step + 1);
487 
488  // If the tolerances are 0, an equality cnt is set
489  if (is_upper_zeros && is_lower_zeros)
490  {
491  trajopt::DblVec single_jnt_coeffs = trajopt::DblVec(num_vels * 2, coeffs[j]);
492  prob.addConstraint(std::make_shared<sco::ConstraintFromErrFunc>(
493  std::make_shared<JointVelErrCalculator>(targets[j], upper_tols[j], lower_tols[j]),
494  std::make_shared<JointVelJacobianCalculator>(), concatVector(joint_vars_vec, time_vars_vec),
495  util::toVectorXd(single_jnt_coeffs), sco::EQ, name + "_j" + std::to_string(j)));
496  }
497  // Otherwise it's a hinged "inequality" constraint
498  else
499  {
500  trajopt::DblVec single_jnt_coeffs = trajopt::DblVec(num_vels * 2, coeffs[j]);
501  prob.addConstraint(std::make_shared<sco::ConstraintFromErrFunc>(
502  std::make_shared<JointVelErrCalculator>(targets[j], upper_tols[j], lower_tols[j]),
503  std::make_shared<JointVelJacobianCalculator>(), concatVector(joint_vars_vec, time_vars_vec),
504  util::toVectorXd(single_jnt_coeffs), sco::INEQ, name + "_j" + std::to_string(j))));
505  }
506  }
507  }
508  else if ((term_type & TT_COST) && ~(term_type | ~TT_USE_TIME))
509  {
510  // If the tolerances are 0, an equality cost is set. Otherwise it's a hinged "inequality" cost
511  if (is_upper_zeros && is_lower_zeros)
512  {
513  prob.addCost(std::make_shared<trajopt::JointVelEqCost>(joint_vars, util::toVectorXd(coeffs),
514  util::toVectorXd(targets), first_step, last_step));
515  prob.getCosts().back()->setName(name);
516  }
517  else
518  {
519  prob.addCost(std::make_shared<trajopt::JointVelIneqCost>(joint_vars, util::toVectorXd(coeffs),
520  util::toVectorXd(targets), util::toVectorXd(upper_tols),
521  util::toVectorXd(lower_tols), first_step, last_step));
522  prob.getCosts().back()->setName(name);
523  }
524  }
525  else if ((term_type & TT_CNT) && ~(term_type | ~TT_USE_TIME))
526  {
527  // If the tolerances are 0, an equality cnt is set. Otherwise it's an inequality constraint
528  if (is_upper_zeros && is_lower_zeros)
529  {
530  prob.addConstraint(std::make_shared<trajopt::JointVelEqConstraint>(
531  joint_vars, util::toVectorXd(coeffs), util::toVectorXd(targets), first_step, last_step));
532  prob.getConstraints().back()->setName(name);
533  }
534  else
535  {
536  prob.addConstraint(std::make_shared<trajopt::JointVelIneqConstraint>(
537  joint_vars, util::toVectorXd(coeffs), util::toVectorXd(targets), util::toVectorXd(upper_tols),
538  util::toVectorXd(lower_tols), first_step, last_step));
539  prob.getConstraints().back()->setName(name);
540  }
541  }
542  else
543  {
544  ROS_WARN("JointVelTermInfo does not have a valid term_type defined. No cost/constraint applied");
545  }
546 }
547 
548 void generateInitialTrajectory(const ProblemInfo& pci, const std::vector<double>& current_joint_values,
549  trajopt::TrajArray& init_traj)
550 {
551  Eigen::VectorXd current_pos(current_joint_values.size());
552  for (int joint_index = 0; joint_index < current_joint_values.size(); ++joint_index)
553  {
554  current_pos(joint_index) = current_joint_values[joint_index];
555  }
556 
557  InitInfo init_info = pci.init_info;
558 
559  // initialize based on type specified
560  if (init_info.type == InitInfo::STATIONARY)
561  {
562  // Initializes all joint values to the initial value (the current value in scene)
563  init_traj = current_pos.transpose().replicate(pci.basic_info.n_steps, 1);
564  }
565  else if (init_info.type == InitInfo::JOINT_INTERPOLATED)
566  {
567  // Linearly interpolates between initial value (current values in the scene) and the joint position specified in
568  // InitInfo.data
569  Eigen::VectorXd end_pos = init_info.data;
570  init_traj.resize(pci.basic_info.n_steps, end_pos.rows());
571  for (int dof_index = 0; dof_index < current_pos.rows(); ++dof_index)
572  {
573  init_traj.col(dof_index) =
574  Eigen::VectorXd::LinSpaced(pci.basic_info.n_steps, current_pos(dof_index), end_pos(dof_index));
575  }
576  }
577  else if (init_info.type == InitInfo::GIVEN_TRAJ)
578  {
579  // Initializes the matrix to a given trajectory
580  init_traj = init_info.data;
581  }
582  else
583  {
584  PRINT_AND_THROW("Init Info did not have a valid type. Valid types are "
585  "STATIONARY, JOINT_INTERPOLATED, or GIVEN_TRAJ");
586  }
587 
588  // Currently all trajectories are generated without time then appended here
589  if (pci.basic_info.use_time)
590  {
591  // add on time (default to 1 sec)
592  init_traj.conservativeResize(Eigen::NoChange_t(), init_traj.cols() + 1);
593 
594  init_traj.block(0, init_traj.cols() - 1, init_traj.rows(), 1) =
595  Eigen::VectorXd::Constant(init_traj.rows(), init_info.dt);
596  }
597 }
598 } // namespace trajopt_interface
const JointBoundsVector & getActiveJointModelsBounds() const
Get the bounds for all the active joints.
const std::vector< std::string > & getActiveJointModelNames() const
Get the names of the active joints in this group. These are the names of the joints returned by getJo...
std::vector< VariableBounds > Bounds
The datatype for the joint bounds.
Definition: joint_model.h:131
Representation of a robot's state. This includes position, velocity, acceleration and effort.
Definition: robot_state.h:90
void copyJointGroupPositions(const std::string &joint_group_name, std::vector< double > &gstate) const
For a given group, copy the position values of the variables that make up the group into another loca...
Definition: robot_state.h:691
const JointModelGroup * getJointModelGroup(const std::string &group) const
Get the model of a particular joint group.
Definition: robot_state.h:134
planning_scene::PlanningSceneConstPtr GetPlanningScene()
sco::VarVector GetVarRow(int i, int start_col, int num_col)
Returns the values of the specified joints (start_col to num_col) for the specified timestep i.
int GetNumDOF()
Returns the problem DOF. This is the number of columns in the optization matrix. Note that this is no...
bool GetHasTime()
Returns TrajOptProb.has_time.
int GetActiveGroupNumDOF()
Returns the kinematic DOF of the active joint model group.
int GetNumSteps()
Returns the number of steps in the problem. This is the number of rows in the optimization matrix.
std::vector< const JointModel::Bounds * > JointBoundsVector
This namespace includes the central class for representing planning contexts.
name
Definition: setup.py:7
Eigen::VectorXd concatVector(const Eigen::VectorXd &vector_a, const Eigen::VectorXd &vector_b)
Appends b to a of type VectorXd.
TrajOptProblemPtr ConstructProblem(const ProblemInfo &)
void generateInitialTrajectory(const ProblemInfo &pci, const std::vector< double > &current_joint_values, trajopt::TrajArray &init_traj)
void checkParameterSize(trajopt::DblVec &parameter, const unsigned int &expected_size, const std::string &name, const bool &apply_first=true)
Checks the size of the parameter given and throws if incorrect.
int n_steps
Number of time steps (rows) in the optimization matrix.
double dt_upper_lim
The upper limit of 1/dt values allowed in the optimization.
double dt_lower_lim
The lower limit of 1/dt values allowed in the optimization.
bool use_time
If true, the last column in the optimization matrix will be 1/dt.
bool start_fixed
If true, first time step is fixed with a joint level constraint If this is false, the starting point ...
Eigen::Vector3d pos_coeffs
coefficients for position and rotation
Eigen::Vector3d xyz
Cartesian position.
std::string link
Link which should reach desired pose.
Eigen::Isometry3d tcp
Static transform applied to the link.
Eigen::Vector4d wxyz
Rotation quaternion.
void addObjectiveTerms(TrajOptProblem &prob) override
Used to add term to pci from json.
int timestep
Timestep at which to apply term.
trajopt::TrajArray data
Data used during initialization. Use depends on the initialization selected. This data will be used t...
Type type
Specifies the type of initialization to use.
double dt
Default value the final column of the optimization is initialized too if time is being used.
int last_step
Last time step to which the term is applied. Default: prob.GetNumSteps() - 1.
trajopt::DblVec upper_tols
Vector of position upper limits. Size should be the DOF of the system. Default: vector of 0's.
trajopt::DblVec coeffs
Vector of coefficients that scale the cost. Size should be the DOF of the system. Default: vector of ...
trajopt::DblVec targets
Vector of position targets. This is a required value. Size should be the DOF of the system.
trajopt::DblVec lower_tols
Vector of position lower limits. Size should be the DOF of the system. Default: vector of 0's.
int first_step
First time step to which the term is applied. Default: 0.
void addObjectiveTerms(TrajOptProblem &prob) override
Converts term info into cost/constraint and adds it to trajopt problem.
void addObjectiveTerms(TrajOptProblem &prob) override
Converts term info into cost/constraint and adds it to trajopt problem.
trajopt::DblVec coeffs
Vector of coefficients that scale the cost. Size should be the DOF of the system. Default: vector of ...
trajopt::DblVec lower_tols
Vector of velocity lower limits. Size should be the DOF of the system. Default: vector of 0's.
trajopt::DblVec targets
Vector of velocity targets. This is a required value. Size should be the DOF of the system.
trajopt::DblVec upper_tols
Vector of velocity upper limits. Size should be the DOF of the system. Default: vector of 0's.
int last_step
Last time step to which the term is applied. Default: prob.GetNumSteps() - 1.
int first_step
First time step to which the term is applied. Default: 0.
std::vector< TermInfoPtr > cnt_infos
std::vector< TermInfoPtr > cost_infos
planning_scene::PlanningSceneConstPtr planning_scene