00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 #include <chomp_motion_planner/chomp_optimizer.h>
00038 #include <ros/ros.h>
00039 #include <visualization_msgs/MarkerArray.h>
00040 #include <chomp_motion_planner/chomp_utils.h>
00041 #include <moveit/robot_model/robot_model.h>
00042 #include <moveit/robot_state/conversions.h>
00043 #include <moveit/planning_scene/planning_scene.h>
00044 #include <eigen3/Eigen/LU>
00045 #include <eigen3/Eigen/Core>
00046
00047 namespace chomp
00048 {
00049 double getRandomDouble()
00050 {
00051 return ((double)random() / (double)RAND_MAX);
00052 }
00053
00054 ChompOptimizer::ChompOptimizer(ChompTrajectory* trajectory, const planning_scene::PlanningSceneConstPtr& planning_scene,
00055 const std::string& planning_group, const ChompParameters* parameters,
00056 const moveit::core::RobotState& start_state)
00057 : full_trajectory_(trajectory)
00058 , kmodel_(planning_scene->getRobotModel())
00059 , planning_group_(planning_group)
00060 , parameters_(parameters)
00061 , group_trajectory_(*full_trajectory_, planning_group_, DIFF_RULE_LENGTH)
00062 , planning_scene_(planning_scene)
00063 , state_(start_state)
00064 , start_state_(start_state)
00065 , initialized_(false)
00066 {
00067 std::vector<std::string> cd_names;
00068 planning_scene->getCollisionDetectorNames(cd_names);
00069
00070 ROS_INFO_STREAM("The following collision detectors are active in the planning scene.");
00071 for (int i = 0; i < cd_names.size(); i++)
00072 {
00073 ROS_INFO_STREAM(cd_names[i]);
00074 }
00075
00076 ROS_INFO_STREAM("Active collision detector is: " + planning_scene->getActiveCollisionDetectorName());
00077
00078
00079
00080 hy_world_ = dynamic_cast<const collision_detection::CollisionWorldHybrid*>(
00081 planning_scene->getCollisionWorld(planning_scene->getActiveCollisionDetectorName()).get());
00082 if (!hy_world_)
00083 {
00084 ROS_WARN_STREAM("Could not initialize hybrid collision world from planning scene");
00085 return;
00086 }
00087
00088 hy_robot_ = dynamic_cast<const collision_detection::CollisionRobotHybrid*>(
00089 planning_scene->getCollisionRobot(planning_scene->getActiveCollisionDetectorName()).get());
00090 if (!hy_robot_)
00091 {
00092 ROS_WARN_STREAM("Could not initialize hybrid collision robot from planning scene");
00093 return;
00094 }
00095 initialize();
00096 }
00097
00098 void ChompOptimizer::initialize()
00099 {
00100
00101 num_vars_free_ = group_trajectory_.getNumFreePoints();
00102 num_vars_all_ = group_trajectory_.getNumPoints();
00103 num_joints_ = group_trajectory_.getNumJoints();
00104
00105 free_vars_start_ = group_trajectory_.getStartIndex();
00106 free_vars_end_ = group_trajectory_.getEndIndex();
00107
00108 collision_detection::CollisionRequest req;
00109 collision_detection::CollisionResult res;
00110 req.group_name = planning_group_;
00111 ros::WallTime wt = ros::WallTime::now();
00112 hy_world_->getCollisionGradients(req, res, *hy_robot_->getCollisionRobotDistanceField().get(), state_,
00113 &planning_scene_->getAllowedCollisionMatrix(), gsr_);
00114 ROS_INFO_STREAM("First coll check took " << (ros::WallTime::now() - wt));
00115 num_collision_points_ = 0;
00116 for (size_t i = 0; i < gsr_->gradients_.size(); i++)
00117 {
00118 num_collision_points_ += gsr_->gradients_[i].gradients.size();
00119 }
00120
00121
00122 joint_costs_.reserve(num_joints_);
00123
00124 double max_cost_scale = 0.0;
00125
00126 joint_model_group_ = planning_scene_->getRobotModel()->getJointModelGroup(planning_group_);
00127
00128 const std::vector<const moveit::core::JointModel*> joint_models = joint_model_group_->getActiveJointModels();
00129 for (size_t i = 0; i < joint_models.size(); i++)
00130 {
00131 const moveit::core::JointModel* model = joint_models[i];
00132 double joint_cost = 1.0;
00133 std::string joint_name = model->getName();
00134
00135 std::vector<double> derivative_costs(3);
00136 derivative_costs[0] = joint_cost * parameters_->getSmoothnessCostVelocity();
00137 derivative_costs[1] = joint_cost * parameters_->getSmoothnessCostAcceleration();
00138 derivative_costs[2] = joint_cost * parameters_->getSmoothnessCostJerk();
00139 joint_costs_.push_back(ChompCost(group_trajectory_, i, derivative_costs, parameters_->getRidgeFactor()));
00140 double cost_scale = joint_costs_[i].getMaxQuadCostInvValue();
00141 if (max_cost_scale < cost_scale)
00142 max_cost_scale = cost_scale;
00143 }
00144
00145
00146 for (int i = 0; i < num_joints_; i++)
00147 {
00148 joint_costs_[i].scale(max_cost_scale);
00149 }
00150
00151
00152 smoothness_increments_ = Eigen::MatrixXd::Zero(num_vars_free_, num_joints_);
00153 collision_increments_ = Eigen::MatrixXd::Zero(num_vars_free_, num_joints_);
00154 final_increments_ = Eigen::MatrixXd::Zero(num_vars_free_, num_joints_);
00155 smoothness_derivative_ = Eigen::VectorXd::Zero(num_vars_all_);
00156 jacobian_ = Eigen::MatrixXd::Zero(3, num_joints_);
00157 jacobian_pseudo_inverse_ = Eigen::MatrixXd::Zero(num_joints_, 3);
00158 jacobian_jacobian_tranpose_ = Eigen::MatrixXd::Zero(3, 3);
00159 random_state_ = Eigen::VectorXd::Zero(num_joints_);
00160 joint_state_velocities_ = Eigen::VectorXd::Zero(num_joints_);
00161
00162 group_trajectory_backup_ = group_trajectory_.getTrajectory();
00163 best_group_trajectory_ = group_trajectory_.getTrajectory();
00164
00165 collision_point_joint_names_.resize(num_vars_all_, std::vector<std::string>(num_collision_points_));
00166 collision_point_pos_eigen_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_collision_points_));
00167 collision_point_vel_eigen_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_collision_points_));
00168 collision_point_acc_eigen_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_collision_points_));
00169 joint_axes_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_joints_));
00170 joint_positions_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_joints_));
00171
00172 collision_point_potential_.resize(num_vars_all_, std::vector<double>(num_collision_points_));
00173 collision_point_vel_mag_.resize(num_vars_all_, std::vector<double>(num_collision_points_));
00174 collision_point_potential_gradient_.resize(num_vars_all_, std::vector<Eigen::Vector3d>(num_collision_points_));
00175
00176 collision_free_iteration_ = 0;
00177 is_collision_free_ = false;
00178 state_is_in_collision_.resize(num_vars_all_);
00179 point_is_in_collision_.resize(num_vars_all_, std::vector<int>(num_collision_points_));
00180
00181 last_improvement_iteration_ = -1;
00182
00183
00184 momentum_ = Eigen::MatrixXd::Zero(num_vars_free_, num_joints_);
00185 random_momentum_ = Eigen::MatrixXd::Zero(num_vars_free_, num_joints_);
00186 random_joint_momentum_ = Eigen::VectorXd::Zero(num_vars_free_);
00187 multivariate_gaussian_.clear();
00188 stochasticity_factor_ = 1.0;
00189 for (int i = 0; i < num_joints_; i++)
00190 {
00191 multivariate_gaussian_.push_back(
00192 MultivariateGaussian(Eigen::VectorXd::Zero(num_vars_free_), joint_costs_[i].getQuadraticCostInverse()));
00193 }
00194
00195 std::map<std::string, std::string> fixed_link_resolution_map;
00196 for (int i = 0; i < num_joints_; i++)
00197 {
00198 joint_names_.push_back(joint_model_group_->getActiveJointModels()[i]->getName());
00199
00200 registerParents(joint_model_group_->getActiveJointModels()[i]);
00201 fixed_link_resolution_map[joint_names_[i]] = joint_names_[i];
00202 }
00203
00204 for (size_t i = 0; i < joint_model_group_->getFixedJointModels().size(); i++)
00205 {
00206 const moveit::core::JointModel* model = joint_model_group_->getFixedJointModels()[i];
00207 fixed_link_resolution_map[model->getName()] = model->getParentLinkModel()->getParentJointModel()->getName();
00208 }
00209
00210
00211 for (size_t i = 0; i < joint_model_group_->getUpdatedLinkModels().size(); i++)
00212 {
00213 if (fixed_link_resolution_map.find(
00214 joint_model_group_->getUpdatedLinkModels()[i]->getParentJointModel()->getName()) ==
00215 fixed_link_resolution_map.end())
00216 {
00217 const moveit::core::JointModel* parent_model = NULL;
00218 bool found_root = false;
00219
00220 while (!found_root)
00221 {
00222 if (parent_model == NULL)
00223 {
00224 parent_model = joint_model_group_->getUpdatedLinkModels()[i]->getParentJointModel();
00225 }
00226 else
00227 {
00228 parent_model = parent_model->getParentLinkModel()->getParentJointModel();
00229 for (size_t j = 0; j < joint_names_.size(); j++)
00230 {
00231 if (parent_model->getName() == joint_names_[j])
00232 {
00233 found_root = true;
00234 }
00235 }
00236 }
00237 }
00238 fixed_link_resolution_map[joint_model_group_->getUpdatedLinkModels()[i]->getParentJointModel()->getName()] =
00239 parent_model->getName();
00240 }
00241 }
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256 int start = free_vars_start_;
00257 int end = free_vars_end_;
00258 for (int i = start; i <= end; ++i)
00259 {
00260 size_t j = 0;
00261 for (size_t g = 0; g < gsr_->gradients_.size(); g++)
00262 {
00263 collision_detection::GradientInfo& info = gsr_->gradients_[g];
00264
00265 for (size_t k = 0; k < info.sphere_locations.size(); k++)
00266 {
00267 if (fixed_link_resolution_map.find(info.joint_name) != fixed_link_resolution_map.end())
00268 {
00269 collision_point_joint_names_[i][j] = fixed_link_resolution_map[info.joint_name];
00270 }
00271 else
00272 {
00273 ROS_ERROR("Couldn't find joint %s!", info.joint_name.c_str());
00274 }
00275 j++;
00276 }
00277 }
00278 }
00279 initialized_ = true;
00280 }
00281
00282 ChompOptimizer::~ChompOptimizer()
00283 {
00284 destroy();
00285 }
00286
00287 void ChompOptimizer::registerParents(const moveit::core::JointModel* model)
00288 {
00289 const moveit::core::JointModel* parent_model = NULL;
00290 bool found_root = false;
00291
00292 if (model == kmodel_->getRootJoint())
00293 return;
00294
00295 while (!found_root)
00296 {
00297 if (parent_model == NULL)
00298 {
00299 if (model->getParentLinkModel() == NULL)
00300 {
00301 ROS_ERROR_STREAM("Model " << model->getName() << " not root but has NULL link model parent");
00302 return;
00303 }
00304 else if (model->getParentLinkModel()->getParentJointModel() == NULL)
00305 {
00306 ROS_ERROR_STREAM("Model " << model->getName() << " not root but has NULL joint model parent");
00307 return;
00308 }
00309 parent_model = model->getParentLinkModel()->getParentJointModel();
00310 }
00311 else
00312 {
00313 if (parent_model == kmodel_->getRootJoint())
00314 {
00315 found_root = true;
00316 }
00317 else
00318 {
00319 parent_model = parent_model->getParentLinkModel()->getParentJointModel();
00320 }
00321 }
00322 joint_parent_map_[model->getName()][parent_model->getName()] = true;
00323 }
00324 }
00325
00326 void ChompOptimizer::optimize()
00327 {
00328 ros::WallTime start_time = ros::WallTime::now();
00329 double averageCostVelocity = 0.0;
00330 int currentCostIter = 0;
00331 int costWindow = 10;
00332 std::vector<double> costs(costWindow, 0.0);
00333 double minimaThreshold = 0.05;
00334 bool should_break_out = false;
00335
00336
00337
00338
00339
00340
00341
00342 for (iteration_ = 0; iteration_ < parameters_->getMaxIterations(); iteration_++)
00343 {
00344 ros::WallTime for_time = ros::WallTime::now();
00345 performForwardKinematics();
00346 ROS_INFO_STREAM("Forward kinematics took " << (ros::WallTime::now() - for_time));
00347 double cCost = getCollisionCost();
00348 double sCost = getSmoothnessCost();
00349 double cost = cCost + sCost;
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369 if (iteration_ == 0)
00370 {
00371 best_group_trajectory_ = group_trajectory_.getTrajectory();
00372 best_group_trajectory_cost_ = cost;
00373 }
00374 else
00375 {
00376 if (cost < best_group_trajectory_cost_)
00377 {
00378 best_group_trajectory_ = group_trajectory_.getTrajectory();
00379 best_group_trajectory_cost_ = cost;
00380 last_improvement_iteration_ = iteration_;
00381 }
00382 }
00383 calculateSmoothnessIncrements();
00384 ros::WallTime coll_time = ros::WallTime::now();
00385 calculateCollisionIncrements();
00386
00387 calculateTotalIncrements();
00388
00389
00390
00391
00392 addIncrementsToTrajectory();
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402 handleJointLimits();
00403 updateFullTrajectory();
00404
00405 if (iteration_ % 10 == 0)
00406 {
00407 ROS_INFO("iteration: %d", iteration_);
00408 if (isCurrentTrajectoryMeshToMeshCollisionFree())
00409 {
00410 num_collision_free_iterations_ = 0;
00411 ROS_INFO("Chomp Got mesh to mesh safety at iter %d. Breaking out early.", iteration_);
00412 is_collision_free_ = true;
00413 iteration_++;
00414 should_break_out = true;
00415 }
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438 }
00439
00440 if (!parameters_->getFilterMode())
00441 {
00442 if (cCost < parameters_->getCollisionThreshold())
00443 {
00444 num_collision_free_iterations_ = parameters_->getMaxIterationsAfterCollisionFree();
00445 is_collision_free_ = true;
00446 iteration_++;
00447 should_break_out = true;
00448 }
00449 else
00450 {
00451
00452 }
00453 }
00454
00455 if ((ros::WallTime::now() - start_time).toSec() > parameters_->getPlanningTimeLimit() &&
00456 !parameters_->getAnimatePath() && !parameters_->getAnimateEndeffector())
00457 {
00458 ROS_WARN("Breaking out early due to time limit constraints.");
00459 break;
00460 }
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498
00499
00500
00501
00502 else if (currentCostIter == -1)
00503 {
00504 currentCostIter = 0;
00505 averageCostVelocity = 0.0;
00506 }
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518 if (should_break_out)
00519 {
00520 collision_free_iteration_++;
00521 if (num_collision_free_iterations_ == 0)
00522 {
00523 break;
00524 }
00525 else if (collision_free_iteration_ > num_collision_free_iterations_)
00526 {
00527
00528
00529
00530
00531
00532 break;
00533 }
00534 }
00535 }
00536
00537 if (is_collision_free_)
00538 {
00539 ROS_INFO("Chomp path is collision free");
00540 }
00541 else
00542 {
00543 ROS_ERROR("Chomp path is not collision free!");
00544 }
00545
00546
00547
00548
00549
00550
00551 group_trajectory_.getTrajectory() = best_group_trajectory_;
00552 updateFullTrajectory();
00553
00554
00555
00556
00557 ROS_INFO("Terminated after %d iterations, using path from iteration %d", iteration_, last_improvement_iteration_);
00558 ROS_INFO("Optimization core finished in %f sec", (ros::WallTime::now() - start_time).toSec());
00559 ROS_INFO_STREAM("Time per iteration " << (ros::WallTime::now() - start_time).toSec() / (iteration_ * 1.0));
00560 }
00561
00562 bool ChompOptimizer::isCurrentTrajectoryMeshToMeshCollisionFree() const
00563 {
00564 moveit_msgs::RobotTrajectory traj;
00565 traj.joint_trajectory.joint_names = joint_names_;
00566
00567 for (int i = 0; i < group_trajectory_.getNumPoints(); i++)
00568 {
00569 trajectory_msgs::JointTrajectoryPoint point;
00570 for (int j = 0; j < group_trajectory_.getNumJoints(); j++)
00571 {
00572 point.positions.push_back(best_group_trajectory_(i, j));
00573 }
00574 traj.joint_trajectory.points.push_back(point);
00575 }
00576 moveit_msgs::RobotState start_state_msg;
00577 moveit::core::robotStateToRobotStateMsg(start_state_, start_state_msg);
00578 return planning_scene_->isPathValid(start_state_msg, traj);
00579 }
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609
00610
00611
00612 void ChompOptimizer::calculateSmoothnessIncrements()
00613 {
00614 for (int i = 0; i < num_joints_; i++)
00615 {
00616 joint_costs_[i].getDerivative(group_trajectory_.getJointTrajectory(i), smoothness_derivative_);
00617 smoothness_increments_.col(i) = -smoothness_derivative_.segment(group_trajectory_.getStartIndex(), num_vars_free_);
00618 }
00619 }
00620
00621 void ChompOptimizer::calculateCollisionIncrements()
00622 {
00623 double potential;
00624 double vel_mag_sq;
00625 double vel_mag;
00626 Eigen::Vector3d potential_gradient;
00627 Eigen::Vector3d normalized_velocity;
00628 Eigen::Matrix3d orthogonal_projector;
00629 Eigen::Vector3d curvature_vector;
00630 Eigen::Vector3d cartesian_gradient;
00631
00632 collision_increments_.setZero(num_vars_free_, num_joints_);
00633
00634 int startPoint = 0;
00635 int endPoint = free_vars_end_;
00636
00637
00638
00639 if (parameters_->getUseStochasticDescent())
00640 {
00641 startPoint = (int)(((double)random() / (double)RAND_MAX) * (free_vars_end_ - free_vars_start_) + free_vars_start_);
00642 if (startPoint < free_vars_start_)
00643 startPoint = free_vars_start_;
00644 if (startPoint > free_vars_end_)
00645 startPoint = free_vars_end_;
00646 endPoint = startPoint;
00647 }
00648 else
00649 {
00650 startPoint = free_vars_start_;
00651 }
00652
00653 for (int i = startPoint; i <= endPoint; i++)
00654 {
00655 for (int j = 0; j < num_collision_points_; j++)
00656 {
00657 potential = collision_point_potential_[i][j];
00658
00659 if (potential < 0.0001)
00660 continue;
00661
00662 potential_gradient = -collision_point_potential_gradient_[i][j];
00663
00664 vel_mag = collision_point_vel_mag_[i][j];
00665 vel_mag_sq = vel_mag * vel_mag;
00666
00667
00668
00669 normalized_velocity = collision_point_vel_eigen_[i][j] / vel_mag;
00670 orthogonal_projector = Eigen::Matrix3d::Identity() - (normalized_velocity * normalized_velocity.transpose());
00671 curvature_vector = (orthogonal_projector * collision_point_acc_eigen_[i][j]) / vel_mag_sq;
00672 cartesian_gradient = vel_mag * (orthogonal_projector * potential_gradient - potential * curvature_vector);
00673
00674
00675 getJacobian(i, collision_point_pos_eigen_[i][j], collision_point_joint_names_[i][j], jacobian_);
00676
00677 if (parameters_->getUsePseudoInverse())
00678 {
00679 calculatePseudoInverse();
00680 collision_increments_.row(i - free_vars_start_).transpose() -= jacobian_pseudo_inverse_ * cartesian_gradient;
00681 }
00682 else
00683 {
00684 collision_increments_.row(i - free_vars_start_).transpose() -= jacobian_.transpose() * cartesian_gradient;
00685 }
00686
00687
00688
00689
00690
00691
00692
00693 }
00694 }
00695
00696 }
00697
00698 void ChompOptimizer::calculatePseudoInverse()
00699 {
00700 jacobian_jacobian_tranpose_ =
00701 jacobian_ * jacobian_.transpose() + Eigen::MatrixXd::Identity(3, 3) * parameters_->getPseudoInverseRidgeFactor();
00702 jacobian_pseudo_inverse_ = jacobian_.transpose() * jacobian_jacobian_tranpose_.inverse();
00703 }
00704
00705 void ChompOptimizer::calculateTotalIncrements()
00706 {
00707 for (int i = 0; i < num_joints_; i++)
00708 {
00709 final_increments_.col(i) =
00710 parameters_->getLearningRate() * (joint_costs_[i].getQuadraticCostInverse() *
00711 (parameters_->getSmoothnessCostWeight() * smoothness_increments_.col(i) +
00712 parameters_->getObstacleCostWeight() * collision_increments_.col(i)));
00713 }
00714 }
00715
00716 void ChompOptimizer::addIncrementsToTrajectory()
00717 {
00718 const std::vector<const moveit::core::JointModel*>& joint_models = joint_model_group_->getActiveJointModels();
00719 for (size_t i = 0; i < joint_models.size(); i++)
00720 {
00721 double scale = 1.0;
00722 double max = final_increments_.col(i).maxCoeff();
00723 double min = final_increments_.col(i).minCoeff();
00724 double max_scale = parameters_->getJointUpdateLimit() / fabs(max);
00725 double min_scale = parameters_->getJointUpdateLimit() / fabs(min);
00726 if (max_scale < scale)
00727 scale = max_scale;
00728 if (min_scale < scale)
00729 scale = min_scale;
00730 group_trajectory_.getFreeTrajectoryBlock().col(i) += scale * final_increments_.col(i);
00731 }
00732
00733
00734 }
00735
00736 void ChompOptimizer::updateFullTrajectory()
00737 {
00738 full_trajectory_->updateFromGroupTrajectory(group_trajectory_);
00739 }
00740
00741 void ChompOptimizer::debugCost()
00742 {
00743 double cost = 0.0;
00744 for (int i = 0; i < num_joints_; i++)
00745 cost += joint_costs_[i].getCost(group_trajectory_.getJointTrajectory(i));
00746 std::cout << "Cost = " << cost << std::endl;
00747 }
00748
00749 double ChompOptimizer::getTrajectoryCost()
00750 {
00751 return getSmoothnessCost() + getCollisionCost();
00752 }
00753
00754 double ChompOptimizer::getSmoothnessCost()
00755 {
00756 double smoothness_cost = 0.0;
00757
00758 for (int i = 0; i < num_joints_; i++)
00759 smoothness_cost += joint_costs_[i].getCost(group_trajectory_.getJointTrajectory(i));
00760
00761 return parameters_->getSmoothnessCostWeight() * smoothness_cost;
00762 }
00763
00764 double ChompOptimizer::getCollisionCost()
00765 {
00766 double collision_cost = 0.0;
00767
00768 double worst_collision_cost = 0.0;
00769 worst_collision_cost_state_ = -1;
00770
00771
00772 for (int i = free_vars_start_; i <= free_vars_end_; i++)
00773 {
00774 double state_collision_cost = 0.0;
00775 for (int j = 0; j < num_collision_points_; j++)
00776 {
00777 state_collision_cost += collision_point_potential_[i][j] * collision_point_vel_mag_[i][j];
00778 }
00779 collision_cost += state_collision_cost;
00780 if (state_collision_cost > worst_collision_cost)
00781 {
00782 worst_collision_cost = state_collision_cost;
00783 worst_collision_cost_state_ = i;
00784 }
00785 }
00786
00787 return parameters_->getObstacleCostWeight() * collision_cost;
00788 }
00789
00790 void ChompOptimizer::computeJointProperties(int trajectory_point)
00791 {
00792
00793 for (int j = 0; j < num_joints_; j++)
00794 {
00795 const moveit::core::JointModel* joint_model = state_.getJointModel(joint_names_[j]);
00796 const moveit::core::RevoluteJointModel* revolute_joint =
00797 dynamic_cast<const moveit::core::RevoluteJointModel*>(joint_model);
00798 const moveit::core::PrismaticJointModel* prismatic_joint =
00799 dynamic_cast<const moveit::core::PrismaticJointModel*>(joint_model);
00800
00801 std::string parent_link_name = joint_model->getParentLinkModel()->getName();
00802 std::string child_link_name = joint_model->getChildLinkModel()->getName();
00803 Eigen::Affine3d joint_transform =
00804 state_.getGlobalLinkTransform(parent_link_name) *
00805 (kmodel_->getLinkModel(child_link_name)->getJointOriginTransform() * (state_.getJointTransform(joint_model)));
00806
00807
00808 Eigen::Vector3d axis;
00809
00810 if (revolute_joint != NULL)
00811 {
00812 axis = revolute_joint->getAxis();
00813 }
00814 else if (prismatic_joint != NULL)
00815 {
00816 axis = prismatic_joint->getAxis();
00817 }
00818 else
00819 {
00820 axis = Eigen::Vector3d::Identity();
00821 }
00822
00823 axis = joint_transform * axis;
00824
00825 joint_axes_[trajectory_point][j] = axis;
00826 joint_positions_[trajectory_point][j] = joint_transform.translation();
00827 }
00828 }
00829
00830 template <typename Derived>
00831 void ChompOptimizer::getJacobian(int trajectory_point, Eigen::Vector3d& collision_point_pos, std::string& joint_name,
00832 Eigen::MatrixBase<Derived>& jacobian) const
00833 {
00834 for (int j = 0; j < num_joints_; j++)
00835 {
00836 if (isParent(joint_name, joint_names_[j]))
00837 {
00838 Eigen::Vector3d column = joint_axes_[trajectory_point][j].cross(
00839 Eigen::Vector3d(collision_point_pos(0), collision_point_pos(1), collision_point_pos(2)) -
00840 joint_positions_[trajectory_point][j]);
00841
00842 jacobian.col(j)[0] = column.x();
00843 jacobian.col(j)[1] = column.y();
00844 jacobian.col(j)[2] = column.z();
00845 }
00846 else
00847 {
00848 jacobian.col(j)[0] = 0.0;
00849 jacobian.col(j)[1] = 0.0;
00850 jacobian.col(j)[2] = 0.0;
00851 }
00852 }
00853 }
00854
00855 void ChompOptimizer::handleJointLimits()
00856 {
00857 const std::vector<const moveit::core::JointModel*> joint_models = joint_model_group_->getActiveJointModels();
00858 for (size_t joint_i = 0; joint_i < joint_models.size(); joint_i++)
00859 {
00860 const moveit::core::JointModel* joint_model = joint_models[joint_i];
00861
00862 if (joint_model->getType() == moveit::core::JointModel::REVOLUTE)
00863 {
00864 const moveit::core::RevoluteJointModel* revolute_joint =
00865 dynamic_cast<const moveit::core::RevoluteJointModel*>(joint_model);
00866 if (revolute_joint->isContinuous())
00867 {
00868 continue;
00869 }
00870 }
00871
00872 const moveit::core::JointModel::Bounds& bounds = joint_model->getVariableBounds();
00873
00874 double joint_max = -DBL_MAX;
00875 double joint_min = DBL_MAX;
00876
00877 for (moveit::core::JointModel::Bounds::const_iterator it = bounds.begin(); it != bounds.end(); it++)
00878 {
00879 if (it->min_position_ < joint_min)
00880 {
00881 joint_min = it->min_position_;
00882 }
00883
00884 if (it->max_position_ > joint_max)
00885 {
00886 joint_max = it->max_position_;
00887 }
00888 }
00889
00890 int count = 0;
00891
00892 bool violation = false;
00893 do
00894 {
00895 double max_abs_violation = 1e-6;
00896 double max_violation = 0.0;
00897 int max_violation_index = 0;
00898 violation = false;
00899 for (int i = free_vars_start_; i <= free_vars_end_; i++)
00900 {
00901 double amount = 0.0;
00902 double absolute_amount = 0.0;
00903 if (group_trajectory_(i, joint_i) > joint_max)
00904 {
00905 amount = joint_max - group_trajectory_(i, joint_i);
00906 absolute_amount = fabs(amount);
00907 }
00908 else if (group_trajectory_(i, joint_i) < joint_min)
00909 {
00910 amount = joint_min - group_trajectory_(i, joint_i);
00911 absolute_amount = fabs(amount);
00912 }
00913 if (absolute_amount > max_abs_violation)
00914 {
00915 max_abs_violation = absolute_amount;
00916 max_violation = amount;
00917 max_violation_index = i;
00918 violation = true;
00919 }
00920 }
00921
00922 if (violation)
00923 {
00924 int free_var_index = max_violation_index - free_vars_start_;
00925 double multiplier =
00926 max_violation / joint_costs_[joint_i].getQuadraticCostInverse()(free_var_index, free_var_index);
00927 group_trajectory_.getFreeJointTrajectoryBlock(joint_i) +=
00928 multiplier * joint_costs_[joint_i].getQuadraticCostInverse().col(free_var_index);
00929 }
00930 if (++count > 10)
00931 break;
00932 } while (violation);
00933 }
00934 }
00935
00936 void ChompOptimizer::performForwardKinematics()
00937 {
00938 double inv_time = 1.0 / group_trajectory_.getDiscretization();
00939 double inv_time_sq = inv_time * inv_time;
00940
00941
00942 int start = free_vars_start_;
00943 int end = free_vars_end_;
00944 if (iteration_ == 0)
00945 {
00946 start = 0;
00947 end = num_vars_all_ - 1;
00948 }
00949
00950 is_collision_free_ = true;
00951
00952 ros::WallDuration total_dur(0.0);
00953
00954
00955 for (int i = start; i <= end; ++i)
00956 {
00957
00958 collision_detection::CollisionRequest req;
00959 collision_detection::CollisionResult res;
00960 req.group_name = planning_group_;
00961 setRobotStateFromPoint(group_trajectory_, i);
00962 ros::WallTime grad = ros::WallTime::now();
00963
00964 hy_world_->getCollisionGradients(req, res, *hy_robot_->getCollisionRobotDistanceField().get(), state_, NULL, gsr_);
00965 total_dur += (ros::WallTime::now() - grad);
00966 computeJointProperties(i);
00967 state_is_in_collision_[i] = false;
00968
00969
00970 {
00971 size_t j = 0;
00972 for (size_t g = 0; g < gsr_->gradients_.size(); g++)
00973 {
00974 collision_detection::GradientInfo& info = gsr_->gradients_[g];
00975
00976 for (size_t k = 0; k < info.sphere_locations.size(); k++)
00977 {
00978 collision_point_pos_eigen_[i][j][0] = info.sphere_locations[k].x();
00979 collision_point_pos_eigen_[i][j][1] = info.sphere_locations[k].y();
00980 collision_point_pos_eigen_[i][j][2] = info.sphere_locations[k].z();
00981
00982 collision_point_potential_[i][j] =
00983 getPotential(info.distances[k], info.sphere_radii[k], parameters_->getMinClearence());
00984 collision_point_potential_gradient_[i][j][0] = info.gradients[k].x();
00985 collision_point_potential_gradient_[i][j][1] = info.gradients[k].y();
00986 collision_point_potential_gradient_[i][j][2] = info.gradients[k].z();
00987
00988 point_is_in_collision_[i][j] = (info.distances[k] - info.sphere_radii[k] < info.sphere_radii[k]);
00989
00990 if (point_is_in_collision_[i][j])
00991 {
00992 state_is_in_collision_[i] = true;
00993
00994
00995
00996
00997
00998
00999
01000
01001
01002 is_collision_free_ = false;
01003 }
01004 j++;
01005 }
01006 }
01007 }
01008 }
01009
01010
01011
01012
01013 for (int i = free_vars_start_; i <= free_vars_end_; i++)
01014 {
01015 for (int j = 0; j < num_collision_points_; j++)
01016 {
01017 collision_point_vel_eigen_[i][j] = Eigen::Vector3d(0, 0, 0);
01018 collision_point_acc_eigen_[i][j] = Eigen::Vector3d(0, 0, 0);
01019 for (int k = -DIFF_RULE_LENGTH / 2; k <= DIFF_RULE_LENGTH / 2; k++)
01020 {
01021 collision_point_vel_eigen_[i][j] +=
01022 (inv_time * DIFF_RULES[0][k + DIFF_RULE_LENGTH / 2]) * collision_point_pos_eigen_[i + k][j];
01023 collision_point_acc_eigen_[i][j] +=
01024 (inv_time_sq * DIFF_RULES[1][k + DIFF_RULE_LENGTH / 2]) * collision_point_pos_eigen_[i + k][j];
01025 }
01026
01027
01028 collision_point_vel_mag_[i][j] = collision_point_vel_eigen_[i][j].norm();
01029 }
01030 }
01031 }
01032
01033 void ChompOptimizer::setRobotStateFromPoint(ChompTrajectory& group_trajectory, int i)
01034 {
01035 const Eigen::MatrixXd::RowXpr& point = group_trajectory.getTrajectoryPoint(i);
01036
01037 std::vector<double> joint_states;
01038 for (int j = 0; j < group_trajectory.getNumJoints(); j++)
01039 {
01040 joint_states.push_back(point(0, j));
01041 }
01042
01043 state_.setJointGroupPositions(planning_group_, joint_states);
01044 state_.update();
01045 }
01046
01047 void ChompOptimizer::perturbTrajectory()
01048 {
01049
01050 if (worst_collision_cost_state_ < 0)
01051 return;
01052 int mid_point = worst_collision_cost_state_;
01053 moveit::core::RobotState random_state = state_;
01054 const moveit::core::JointModelGroup* planning_group = state_.getJointModelGroup(planning_group_);
01055 random_state.setToRandomPositions(planning_group);
01056 std::vector<double> vals;
01057 random_state.copyJointGroupPositions(planning_group_, vals);
01058 double* ptr = &vals[0];
01059 Eigen::Map<Eigen::VectorXd> random_matrix(ptr, vals.size());
01060
01061
01062
01063 random_matrix -= group_trajectory_.getTrajectoryPoint(mid_point).transpose();
01064
01065
01066 group_trajectory_.getJointVelocities(mid_point, joint_state_velocities_);
01067 joint_state_velocities_.normalize();
01068 random_matrix = (Eigen::MatrixXd::Identity(num_joints_, num_joints_) -
01069 joint_state_velocities_ * joint_state_velocities_.transpose()) *
01070 random_matrix;
01071
01072 int mp_free_vars_index = mid_point - free_vars_start_;
01073 for (int i = 0; i < num_joints_; i++)
01074 {
01075 group_trajectory_.getFreeJointTrajectoryBlock(i) +=
01076 joint_costs_[i].getQuadraticCostInverse().col(mp_free_vars_index) * random_state_(i);
01077 }
01078 }
01079
01080
01081
01082
01083
01084
01085
01086
01087
01088
01089
01090
01091
01092
01093
01094
01095
01096
01097
01098
01099
01100
01101
01102
01103
01104
01105
01106
01107
01108
01109
01110
01111
01112
01113
01114
01115
01116
01117
01118
01119
01120
01121
01122
01123
01124
01125
01126
01127 void ChompOptimizer::getRandomMomentum()
01128 {
01129 if (is_collision_free_)
01130 random_momentum_.setZero(num_vars_free_, num_joints_);
01131 else
01132 for (int i = 0; i < num_joints_; ++i)
01133 {
01134 multivariate_gaussian_[i].sample(random_joint_momentum_);
01135 random_momentum_.col(i) = stochasticity_factor_ * random_joint_momentum_;
01136 }
01137 }
01138
01139 void ChompOptimizer::updateMomentum()
01140 {
01141
01142 double eps = parameters_->getHmcDiscretization();
01143 if (iteration_ > 0)
01144 momentum_ = (momentum_ + eps * final_increments_);
01145 else
01146 momentum_ = random_momentum_;
01147
01148 }
01149
01150 void ChompOptimizer::updatePositionFromMomentum()
01151 {
01152 double eps = parameters_->getHmcDiscretization();
01153 group_trajectory_.getFreeTrajectoryBlock() += eps * momentum_;
01154 }
01155
01156
01157
01158
01159
01160
01161
01162
01163
01164
01165
01166
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201
01202
01203
01204
01205
01206
01207
01208
01209
01210
01211
01212
01213
01214
01215
01216
01217
01218
01219
01220
01221
01222
01223
01224
01225
01226
01227
01228
01229
01230
01231
01232
01233
01234
01235
01236
01237
01238
01239
01240
01241
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266
01267 }