ekf_localizer.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. /*
  2. * Copyright 2018-2019 Autoware Foundation. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "ekf_localizer.h"
  17. // clang-format off
  18. #define PRINT_MAT(X) std::cout << #X << ":\n" << X << std::endl << std::endl
  19. //#define DEBUG_INFO(...) { if (show_debug_info_) { ROS_INFO(__VA_ARGS__); } }
  20. #define DEBUG_INFO(...) {if (show_debug_info_){ printf(__VA_ARGS__); } }
  21. #define DEBUG_PRINT_MAT(X) { if (show_debug_info_) { std::cout << #X << ": " << X << std::endl; } }
  22. static int mnNoData = 100;
  23. // clang-format on
  24. EKFLocalizer::EKFLocalizer()
  25. {
  26. dim_x_ = 6;
  27. show_debug_info_ = false;
  28. ekf_rate_ = 100.0;
  29. ekf_dt_ = 1.0 / std::max(ekf_rate_, 0.1);
  30. tf_rate_ = 1.0;
  31. enable_yaw_bias_estimation_ = true;
  32. extend_state_step_ = 50;
  33. pose_frame_id_ = "/map";
  34. pose_additional_delay_ = 0.0;
  35. pose_measure_uncertainty_time_ = 0.01;
  36. pose_rate_ = 10.0;
  37. pose_gate_dist_ = 10000.0;
  38. pose_stddev_x_ = 0.05;
  39. pose_stddev_y_ = 0.05;
  40. pose_stddev_yaw_ = 0.035;
  41. use_pose_with_covariance_ = false;
  42. // pnh_.param("show_debug_info", show_debug_info_, bool(false));
  43. // pnh_.param("predict_frequency", ekf_rate_, double(50.0));
  44. // ekf_dt_ = 1.0 / std::max(ekf_rate_, 0.1);
  45. // pnh_.param("tf_rate", tf_rate_, double(10.0));
  46. // pnh_.param("enable_yaw_bias_estimation", enable_yaw_bias_estimation_, bool(true));
  47. // pnh_.param("extend_state_step", extend_state_step_, int(50));
  48. // pnh_.param("pose_frame_id", pose_frame_id_, std::string("/map"));
  49. // /* pose measurement */
  50. // pnh_.param("pose_additional_delay", pose_additional_delay_, double(0.0));
  51. // pnh_.param("pose_measure_uncertainty_time", pose_measure_uncertainty_time_, double(0.01));
  52. // pnh_.param("pose_rate", pose_rate_, double(10.0)); // used for covariance calculation
  53. // pnh_.param("pose_gate_dist", pose_gate_dist_, double(10000.0)); // Mahalanobis limit
  54. // pnh_.param("pose_stddev_x", pose_stddev_x_, double(0.05));
  55. // pnh_.param("pose_stddev_y", pose_stddev_y_, double(0.05));
  56. // pnh_.param("pose_stddev_yaw", pose_stddev_yaw_, double(0.035));
  57. // pnh_.param("use_pose_with_covariance", use_pose_with_covariance_, bool(false));
  58. twist_additional_delay_ = 0.0;
  59. twist_rate_ = 10.0;
  60. twist_gate_dist_ = 10000.0;
  61. twist_stddev_vx_ = 0.2;
  62. twist_stddev_wz_ = 0.03;
  63. use_twist_with_covariance_ = false;
  64. // /* twist measurement */
  65. // pnh_.param("twist_additional_delay", twist_additional_delay_, double(0.0));
  66. // pnh_.param("twist_rate", twist_rate_, double(10.0)); // used for covariance calculation
  67. // pnh_.param("twist_gate_dist", twist_gate_dist_, double(10000.0)); // Mahalanobis limit
  68. // pnh_.param("twist_stddev_vx", twist_stddev_vx_, double(0.2));
  69. // pnh_.param("twist_stddev_wz", twist_stddev_wz_, double(0.03));
  70. // pnh_.param("use_twist_with_covariance", use_twist_with_covariance_, bool(false));
  71. /* process noise */
  72. double proc_stddev_yaw_c, proc_stddev_yaw_bias_c, proc_stddev_vx_c, proc_stddev_wz_c;
  73. // pnh_.param("proc_stddev_yaw_c", proc_stddev_yaw_c, double(0.005));
  74. // pnh_.param("proc_stddev_yaw_bias_c", proc_stddev_yaw_bias_c, double(0.001));
  75. // pnh_.param("proc_stddev_vx_c", proc_stddev_vx_c, double(2.0));
  76. // pnh_.param("proc_stddev_wz_c", proc_stddev_wz_c, double(0.2));
  77. proc_stddev_yaw_c = 0.005;
  78. proc_stddev_yaw_bias_c = 0.001;
  79. proc_stddev_vx_c = 2.0;
  80. proc_stddev_wz_c = 0.2;
  81. if (!enable_yaw_bias_estimation_)
  82. {
  83. proc_stddev_yaw_bias_c = 0.0;
  84. }
  85. /* convert to continuous to discrete */
  86. proc_cov_vx_d_ = std::pow(proc_stddev_vx_c, 2.0) * ekf_dt_;
  87. proc_cov_wz_d_ = std::pow(proc_stddev_wz_c, 2.0) * ekf_dt_;
  88. proc_cov_yaw_d_ = std::pow(proc_stddev_yaw_c, 2.0) * ekf_dt_;
  89. proc_cov_yaw_bias_d_ = std::pow(proc_stddev_yaw_bias_c, 2.0) * ekf_dt_;
  90. /* initialize ros system */
  91. // timer_control_ = nh_.createTimer(ros::Duration(ekf_dt_), &EKFLocalizer::timerCallback, this);
  92. // timer_tf_ = nh_.createTimer(ros::Duration(1.0 / tf_rate_), &EKFLocalizer::timerTFCallback, this);
  93. // pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>("ekf_pose", 1);
  94. // pub_pose_cov_ = nh_.advertise<geometry_msgs::PoseWithCovarianceStamped>("ekf_pose_with_covariance", 1);
  95. // pub_twist_ = nh_.advertise<geometry_msgs::TwistStamped>("ekf_twist", 1);
  96. // pub_twist_cov_ = nh_.advertise<geometry_msgs::TwistWithCovarianceStamped>("ekf_twist_with_covariance", 1);
  97. // pub_yaw_bias_ = pnh_.advertise<std_msgs::Float64>("estimated_yaw_bias", 1);
  98. // sub_initialpose_ = nh_.subscribe("initialpose", 1, &EKFLocalizer::callbackInitialPose, this);
  99. // sub_pose_with_cov_ = nh_.subscribe("in_pose_with_covariance", 1, &EKFLocalizer::callbackPoseWithCovariance, this);
  100. // sub_pose_ = nh_.subscribe("in_pose", 1, &EKFLocalizer::callbackPose, this);
  101. // sub_twist_with_cov_ = nh_.subscribe("in_twist_with_covariance", 1, &EKFLocalizer::callbackTwistWithCovariance, this);
  102. // sub_twist_ = nh_.subscribe("in_twist", 1, &EKFLocalizer::callbackTwist, this);
  103. dim_x_ex_ = dim_x_ * extend_state_step_;
  104. initEKF();
  105. mpandtekf = iv::modulecomm::RegisterSend("ndtekf",100000,1);
  106. mpthread = new std::thread(&EKFLocalizer::timerthread,this);
  107. ModuleFun fungps = std::bind(&EKFLocalizer::UpdateGPS,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3,std::placeholders::_4,std::placeholders::_5);
  108. mpa = iv::modulecomm::RegisterRecvPlus("ndtpos",fungps);
  109. /* debug */
  110. // pub_debug_ = pnh_.advertise<std_msgs::Float64MultiArray>("debug", 1);
  111. // pub_measured_pose_ = pnh_.advertise<geometry_msgs::PoseStamped>("debug/measured_pose", 1);
  112. };
  113. EKFLocalizer::~EKFLocalizer(){};
  114. ///*
  115. // * timerCallback
  116. // */
  117. //void EKFLocalizer::timerCallback(const ros::TimerEvent& e)
  118. //{
  119. // DEBUG_INFO("========================= timer called =========================");
  120. // /* predict model in EKF */
  121. // auto start = std::chrono::system_clock::now();
  122. // DEBUG_INFO("------------------------- start prediction -------------------------");
  123. // predictKinematicsModel();
  124. // double elapsed =
  125. // std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  126. // DEBUG_INFO("[EKF] predictKinematicsModel calculation time = %f [ms]", elapsed * 1.0e-6);
  127. // DEBUG_INFO("------------------------- end prediction -------------------------\n");
  128. //// /* pose measurement update */
  129. //// if (current_pose_ptr_ != nullptr)
  130. //// {
  131. //// DEBUG_INFO("------------------------- start Pose -------------------------");
  132. //// start = std::chrono::system_clock::now();
  133. //// measurementUpdatePose(*current_pose_ptr_);
  134. //// elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  135. //// DEBUG_INFO("[EKF] measurementUpdatePose calculation time = %f [ms]", elapsed * 1.0e-6);
  136. //// DEBUG_INFO("------------------------- end Pose -------------------------\n");
  137. //// }
  138. //// /* twist measurement update */
  139. //// if (current_twist_ptr_ != nullptr)
  140. //// {
  141. //// DEBUG_INFO("------------------------- start twist -------------------------");
  142. //// start = std::chrono::system_clock::now();
  143. //// measurementUpdateTwist(*current_twist_ptr_);
  144. //// elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  145. //// DEBUG_INFO("[EKF] measurementUpdateTwist calculation time = %f [ms]", elapsed * 1.0e-6);
  146. //// DEBUG_INFO("------------------------- end twist -------------------------\n");
  147. //// }
  148. // /* set current pose, twist */
  149. // setCurrentResult();
  150. // /* publish ekf result */
  151. // publishEstimateResult();
  152. //}
  153. //void EKFLocalizer::showCurrentX()
  154. //{
  155. // if (show_debug_info_)
  156. // {
  157. // Eigen::MatrixXd X(dim_x_, 1);
  158. // ekf_.getLatestX(X);
  159. // DEBUG_PRINT_MAT(X.transpose());
  160. // }
  161. //}
  162. ///*
  163. // * setCurrentResult
  164. // */
  165. //void EKFLocalizer::setCurrentResult()
  166. //{
  167. // current_ekf_pose_.header.frame_id = pose_frame_id_;
  168. // current_ekf_pose_.header.stamp = ros::Time::now();
  169. // current_ekf_pose_.pose.position.x = ekf_.getXelement(IDX::X);
  170. // current_ekf_pose_.pose.position.y = ekf_.getXelement(IDX::Y);
  171. // tf2::Quaternion q_tf;
  172. // double roll, pitch, yaw;
  173. // if (current_pose_ptr_ != nullptr)
  174. // {
  175. // current_ekf_pose_.pose.position.z = current_pose_ptr_->pose.position.z;
  176. // tf2::fromMsg(current_pose_ptr_->pose.orientation, q_tf); /* use Pose pitch and roll */
  177. // tf2::Matrix3x3(q_tf).getRPY(roll, pitch, yaw);
  178. // }
  179. // else
  180. // {
  181. // current_ekf_pose_.pose.position.z = 0.0;
  182. // roll = 0;
  183. // pitch = 0;
  184. // }
  185. // yaw = ekf_.getXelement(IDX::YAW) + ekf_.getXelement(IDX::YAWB);
  186. // q_tf.setRPY(roll, pitch, yaw);
  187. // tf2::convert(q_tf, current_ekf_pose_.pose.orientation);
  188. // current_ekf_twist_.header.frame_id = "base_link";
  189. // current_ekf_twist_.header.stamp = ros::Time::now();
  190. // current_ekf_twist_.twist.linear.x = ekf_.getXelement(IDX::VX);
  191. // current_ekf_twist_.twist.angular.z = ekf_.getXelement(IDX::WZ);
  192. //}
  193. ///*
  194. // * timerTFCallback
  195. // */
  196. //void EKFLocalizer::timerTFCallback(const ros::TimerEvent& e)
  197. //{
  198. // if (current_ekf_pose_.header.frame_id == "")
  199. // return;
  200. // geometry_msgs::TransformStamped transformStamped;
  201. // transformStamped.header.stamp = ros::Time::now();
  202. // transformStamped.header.frame_id = current_ekf_pose_.header.frame_id;
  203. // transformStamped.child_frame_id = "ekf_pose";
  204. // transformStamped.transform.translation.x = current_ekf_pose_.pose.position.x;
  205. // transformStamped.transform.translation.y = current_ekf_pose_.pose.position.y;
  206. // transformStamped.transform.translation.z = current_ekf_pose_.pose.position.z;
  207. // transformStamped.transform.rotation.x = current_ekf_pose_.pose.orientation.x;
  208. // transformStamped.transform.rotation.y = current_ekf_pose_.pose.orientation.y;
  209. // transformStamped.transform.rotation.z = current_ekf_pose_.pose.orientation.z;
  210. // transformStamped.transform.rotation.w = current_ekf_pose_.pose.orientation.w;
  211. // tf_br_.sendTransform(transformStamped);
  212. //}
  213. ///*
  214. // * getTransformFromTF
  215. // */
  216. //bool EKFLocalizer::getTransformFromTF(std::string parent_frame, std::string child_frame,
  217. // geometry_msgs::TransformStamped& transform)
  218. //{
  219. // tf2_ros::Buffer tf_buffer;
  220. // tf2_ros::TransformListener tf_listener(tf_buffer);
  221. // ros::Duration(0.1).sleep();
  222. // if (parent_frame.front() == '/')
  223. // parent_frame.erase(0, 1);
  224. // if (child_frame.front() == '/')
  225. // child_frame.erase(0, 1);
  226. // for (int i = 0; i < 50; ++i)
  227. // {
  228. // try
  229. // {
  230. // transform = tf_buffer.lookupTransform(parent_frame, child_frame, ros::Time(0));
  231. // return true;
  232. // }
  233. // catch (tf2::TransformException& ex)
  234. // {
  235. // ROS_WARN("%s", ex.what());
  236. // ros::Duration(0.1).sleep();
  237. // }
  238. // }
  239. // return false;
  240. //}
  241. ///*
  242. // * callbackInitialPose
  243. // */
  244. //void EKFLocalizer::callbackInitialPose(const geometry_msgs::PoseWithCovarianceStamped& initialpose)
  245. //{
  246. // geometry_msgs::TransformStamped transform;
  247. // if (!getTransformFromTF(pose_frame_id_, initialpose.header.frame_id, transform))
  248. // {
  249. // ROS_ERROR("[EKF] TF transform failed. parent = %s, child = %s", pose_frame_id_.c_str(),
  250. // initialpose.header.frame_id.c_str());
  251. // };
  252. // Eigen::MatrixXd X(dim_x_, 1);
  253. // Eigen::MatrixXd P = Eigen::MatrixXd::Zero(dim_x_, dim_x_);
  254. // X(IDX::X) = initialpose.pose.pose.position.x + transform.transform.translation.x;
  255. // X(IDX::Y) = initialpose.pose.pose.position.y + transform.transform.translation.y;
  256. // X(IDX::YAW) = tf2::getYaw(initialpose.pose.pose.orientation) + tf2::getYaw(transform.transform.rotation);
  257. // X(IDX::YAWB) = 0.0;
  258. // X(IDX::VX) = 0.0;
  259. // X(IDX::WZ) = 0.0;
  260. // P(IDX::X, IDX::X) = initialpose.pose.covariance[0];
  261. // P(IDX::Y, IDX::Y) = initialpose.pose.covariance[6 + 1];
  262. // P(IDX::YAW, IDX::YAW) = initialpose.pose.covariance[6 * 5 + 5];
  263. // P(IDX::YAWB, IDX::YAWB) = 0.0001;
  264. // P(IDX::VX, IDX::VX) = 0.01;
  265. // P(IDX::WZ, IDX::WZ) = 0.01;
  266. // ekf_.init(X, P, extend_state_step_);
  267. //};
  268. ///*
  269. // * callbackPose
  270. // */
  271. //void EKFLocalizer::callbackPose(const geometry_msgs::PoseStamped::ConstPtr& msg)
  272. //{
  273. // if (!use_pose_with_covariance_)
  274. // {
  275. // current_pose_ptr_ = std::make_shared<geometry_msgs::PoseStamped>(*msg);
  276. // }
  277. //};
  278. ///*
  279. // * callbackPoseWithCovariance
  280. // */
  281. //void EKFLocalizer::callbackPoseWithCovariance(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
  282. //{
  283. // if (use_pose_with_covariance_)
  284. // {
  285. // geometry_msgs::PoseStamped pose;
  286. // pose.header = msg->header;
  287. // pose.pose = msg->pose.pose;
  288. // current_pose_ptr_ = std::make_shared<geometry_msgs::PoseStamped>(pose);
  289. // current_pose_covariance_ = msg->pose.covariance;
  290. // }
  291. //};
  292. ///*
  293. // * callbackTwist
  294. // */
  295. //void EKFLocalizer::callbackTwist(const geometry_msgs::TwistStamped::ConstPtr& msg)
  296. //{
  297. // if (!use_twist_with_covariance_)
  298. // {
  299. // current_twist_ptr_ = std::make_shared<geometry_msgs::TwistStamped>(*msg);
  300. // }
  301. //};
  302. ///*
  303. // * callbackTwistWithCovariance
  304. // */
  305. //void EKFLocalizer::callbackTwistWithCovariance(const geometry_msgs::TwistWithCovarianceStamped::ConstPtr& msg)
  306. //{
  307. // if (use_twist_with_covariance_)
  308. // {
  309. // geometry_msgs::TwistStamped twist;
  310. // twist.header = msg->header;
  311. // twist.twist = msg->twist.twist;
  312. // current_twist_ptr_ = std::make_shared<geometry_msgs::TwistStamped>(twist);
  313. // current_twist_covariance_ = msg->twist.covariance;
  314. // }
  315. //};
  316. /*
  317. * initEKF
  318. */
  319. void EKFLocalizer::initEKF()
  320. {
  321. Eigen::MatrixXd X = Eigen::MatrixXd::Zero(dim_x_, 1);
  322. Eigen::MatrixXd P = Eigen::MatrixXd::Identity(dim_x_, dim_x_) * 1.0E15; // for x & y
  323. P(IDX::YAW, IDX::YAW) = 50.0; // for yaw
  324. P(IDX::YAWB, IDX::YAWB) = proc_cov_yaw_bias_d_; // for yaw bias
  325. P(IDX::VX, IDX::VX) = 1000.0; // for vx
  326. P(IDX::WZ, IDX::WZ) = 50.0; // for wz
  327. ekf_.init(X, P, extend_state_step_);
  328. }
  329. /*
  330. * predictKinematicsModel
  331. */
  332. void EKFLocalizer::predictKinematicsModel()
  333. {
  334. /* == Nonlinear model ==
  335. *
  336. * x_{k+1} = x_k + vx_k * cos(yaw_k + b_k) * dt
  337. * y_{k+1} = y_k + vx_k * sin(yaw_k + b_k) * dt
  338. * yaw_{k+1} = yaw_k + (wz_k) * dt
  339. * b_{k+1} = b_k
  340. * vx_{k+1} = vz_k
  341. * wz_{k+1} = wz_k
  342. *
  343. * (b_k : yaw_bias_k)
  344. */
  345. /* == Linearized model ==
  346. *
  347. * A = [ 1, 0, -vx*sin(yaw+b)*dt, -vx*sin(yaw+b)*dt, cos(yaw+b)*dt, 0]
  348. * [ 0, 1, vx*cos(yaw+b)*dt, vx*cos(yaw+b)*dt, sin(yaw+b)*dt, 0]
  349. * [ 0, 0, 1, 0, 0, dt]
  350. * [ 0, 0, 0, 1, 0, 0]
  351. * [ 0, 0, 0, 0, 1, 0]
  352. * [ 0, 0, 0, 0, 0, 1]
  353. */
  354. Eigen::MatrixXd X_curr(dim_x_, 1); // curent state
  355. Eigen::MatrixXd X_next(dim_x_, 1); // predicted state
  356. ekf_.getLatestX(X_curr);
  357. DEBUG_PRINT_MAT(X_curr.transpose());
  358. Eigen::MatrixXd P_curr;
  359. ekf_.getLatestP(P_curr);
  360. const int d_dim_x = dim_x_ex_ - dim_x_;
  361. const double yaw = X_curr(IDX::YAW);
  362. const double yaw_bias = X_curr(IDX::YAWB);
  363. const double vx = X_curr(IDX::VX);
  364. const double wz = X_curr(IDX::WZ);
  365. const double dt = ekf_dt_;
  366. /* Update for latest state */
  367. X_next(IDX::X) = X_curr(IDX::X) + vx * cos(yaw + yaw_bias) * dt; // dx = v * cos(yaw)
  368. X_next(IDX::Y) = X_curr(IDX::Y) + vx * sin(yaw + yaw_bias) * dt; // dy = v * sin(yaw)
  369. X_next(IDX::YAW) = X_curr(IDX::YAW) + (wz)*dt; // dyaw = omega + omega_bias
  370. X_next(IDX::YAWB) = yaw_bias;
  371. X_next(IDX::VX) = vx;
  372. X_next(IDX::WZ) = wz;
  373. X_next(IDX::YAW) = std::atan2(std::sin(X_next(IDX::YAW)), std::cos(X_next(IDX::YAW)));
  374. /* Set A matrix for latest state */
  375. Eigen::MatrixXd A = Eigen::MatrixXd::Identity(dim_x_, dim_x_);
  376. A(IDX::X, IDX::YAW) = -vx * sin(yaw + yaw_bias) * dt;
  377. A(IDX::X, IDX::YAWB) = -vx * sin(yaw + yaw_bias) * dt;
  378. A(IDX::X, IDX::VX) = cos(yaw + yaw_bias) * dt;
  379. A(IDX::Y, IDX::YAW) = vx * cos(yaw + yaw_bias) * dt;
  380. A(IDX::Y, IDX::YAWB) = vx * cos(yaw + yaw_bias) * dt;
  381. A(IDX::Y, IDX::VX) = sin(yaw + yaw_bias) * dt;
  382. A(IDX::YAW, IDX::WZ) = dt;
  383. const double dvx = std::sqrt(P_curr(IDX::VX, IDX::VX));
  384. const double dyaw = std::sqrt(P_curr(IDX::YAW, IDX::YAW));
  385. Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(dim_x_, dim_x_);
  386. if (dvx < 10.0 && dyaw < 1.0)
  387. {
  388. // auto covariance calculate for x, y assuming vx & yaw estimation covariance is small
  389. /* Set covariance matrix Q for process noise. Calc Q by velocity and yaw angle covariance :
  390. dx = Ax + Jp*w -> Q = Jp*w_cov*Jp' */
  391. Eigen::MatrixXd Jp = Eigen::MatrixXd::Zero(2, 2); // coeff of deviation of vx & yaw
  392. Jp << cos(yaw), -vx * sin(yaw), sin(yaw), vx * cos(yaw);
  393. Eigen::MatrixXd Q_vx_yaw = Eigen::MatrixXd::Zero(2, 2); // cov of vx and yaw
  394. Q_vx_yaw(0, 0) = P_curr(IDX::VX, IDX::VX) * dt; // covariance of vx - vx
  395. Q_vx_yaw(1, 1) = P_curr(IDX::YAW, IDX::YAW) * dt; // covariance of yaw - yaw
  396. Q_vx_yaw(0, 1) = P_curr(IDX::VX, IDX::YAW) * dt; // covariance of vx - yaw
  397. Q_vx_yaw(1, 0) = P_curr(IDX::YAW, IDX::VX) * dt; // covariance of yaw - vx
  398. Q.block(0, 0, 2, 2) = Jp * Q_vx_yaw * Jp.transpose(); // for pos_x & pos_y
  399. }
  400. else
  401. {
  402. // vx & vy is not converged yet, set constant value.
  403. Q(IDX::X, IDX::X) = 0.05;
  404. Q(IDX::Y, IDX::Y) = 0.05;
  405. }
  406. Q(IDX::YAW, IDX::YAW) = proc_cov_yaw_d_; // for yaw
  407. Q(IDX::YAWB, IDX::YAWB) = proc_cov_yaw_bias_d_; // for yaw bias
  408. Q(IDX::VX, IDX::VX) = proc_cov_vx_d_; // for vx
  409. Q(IDX::WZ, IDX::WZ) = proc_cov_wz_d_; // for wz
  410. ekf_.predictWithDelay(X_next, A, Q);
  411. // debug
  412. Eigen::MatrixXd X_result(dim_x_, 1);
  413. ekf_.getLatestX(X_result);
  414. DEBUG_PRINT_MAT(X_result.transpose());
  415. DEBUG_PRINT_MAT((X_result - X_curr).transpose());
  416. }
  417. /*
  418. * measurementUpdatePose
  419. */
  420. //void EKFLocalizer::measurementUpdatePose(const geometry_msgs::PoseStamped& pose)
  421. //{
  422. // if (pose.header.frame_id != pose_frame_id_)
  423. // {
  424. // ROS_WARN_DELAYED_THROTTLE(2, "pose frame_id is %s, but pose_frame is set as %s. They must be same.",
  425. // pose.header.frame_id.c_str(), pose_frame_id_.c_str());
  426. // }
  427. // Eigen::MatrixXd X_curr(dim_x_, 1); // curent state
  428. // ekf_.getLatestX(X_curr);
  429. // DEBUG_PRINT_MAT(X_curr.transpose());
  430. // constexpr int dim_y = 3; // pos_x, pos_y, yaw, depending on Pose output
  431. // const ros::Time t_curr = ros::Time::now();
  432. // /* Calculate delay step */
  433. // double delay_time = (t_curr - pose.header.stamp).toSec() + pose_additional_delay_;
  434. // if (delay_time < 0.0)
  435. // {
  436. // delay_time = 0.0;
  437. // ROS_WARN_DELAYED_THROTTLE(1.0, "Pose time stamp is inappropriate, set delay to 0[s]. delay = %f", delay_time);
  438. // }
  439. // int delay_step = std::roundf(delay_time / ekf_dt_);
  440. // if (delay_step > extend_state_step_ - 1)
  441. // {
  442. // ROS_WARN_DELAYED_THROTTLE(1.0,
  443. // "Pose delay exceeds the compensation limit, ignored. delay: %f[s], limit = "
  444. // "extend_state_step * ekf_dt : %f [s]",
  445. // delay_time, extend_state_step_ * ekf_dt_);
  446. // return;
  447. // }
  448. // DEBUG_INFO("delay_time: %f [s]", delay_time);
  449. // /* Set yaw */
  450. // const double yaw_curr = ekf_.getXelement((unsigned int)(delay_step * dim_x_ + IDX::YAW));
  451. // double yaw = tf2::getYaw(pose.pose.orientation);
  452. // const double ekf_yaw = ekf_.getXelement(delay_step * dim_x_ + IDX::YAW);
  453. // const double yaw_error = normalizeYaw(yaw - ekf_yaw); // normalize the error not to exceed 2 pi
  454. // yaw = yaw_error + ekf_yaw;
  455. // /* Set measurement matrix */
  456. // Eigen::MatrixXd y(dim_y, 1);
  457. // y << pose.pose.position.x, pose.pose.position.y, yaw;
  458. // if (isnan(y.array()).any() || isinf(y.array()).any())
  459. // {
  460. // ROS_WARN("[EKF] pose measurement matrix includes NaN of Inf. ignore update. check pose message.");
  461. // return;
  462. // }
  463. // /* Gate */
  464. // Eigen::MatrixXd y_ekf(dim_y, 1);
  465. // y_ekf << ekf_.getXelement(delay_step * dim_x_ + IDX::X), ekf_.getXelement(delay_step * dim_x_ + IDX::Y), ekf_yaw;
  466. // Eigen::MatrixXd P_curr, P_y;
  467. // ekf_.getLatestP(P_curr);
  468. // P_y = P_curr.block(0, 0, dim_y, dim_y);
  469. // if (!mahalanobisGate(pose_gate_dist_, y_ekf, y, P_y))
  470. // {
  471. // ROS_WARN_DELAYED_THROTTLE(2.0, "[EKF] Pose measurement update, mahalanobis distance is over limit. ignore "
  472. // "measurement data.");
  473. // return;
  474. // }
  475. // DEBUG_PRINT_MAT(y.transpose());
  476. // DEBUG_PRINT_MAT(y_ekf.transpose());
  477. // DEBUG_PRINT_MAT((y - y_ekf).transpose());
  478. // /* Set measurement matrix */
  479. // Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim_y, dim_x_);
  480. // C(0, IDX::X) = 1.0; // for pos x
  481. // C(1, IDX::Y) = 1.0; // for pos y
  482. // C(2, IDX::YAW) = 1.0; // for yaw
  483. // /* Set measurement noise covariancs */
  484. // Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_y, dim_y);
  485. // if (use_pose_with_covariance_)
  486. // {
  487. // R(0, 0) = current_pose_covariance_.at(0); // x - x
  488. // R(0, 1) = current_pose_covariance_.at(1); // x - y
  489. // R(0, 2) = current_pose_covariance_.at(5); // x - yaw
  490. // R(1, 0) = current_pose_covariance_.at(6); // y - x
  491. // R(1, 1) = current_pose_covariance_.at(7); // y - y
  492. // R(1, 2) = current_pose_covariance_.at(11); // y - yaw
  493. // R(2, 0) = current_pose_covariance_.at(30); // yaw - x
  494. // R(2, 1) = current_pose_covariance_.at(31); // yaw - y
  495. // R(2, 2) = current_pose_covariance_.at(35); // yaw - yaw
  496. // }
  497. // else
  498. // {
  499. // const double ekf_yaw = ekf_.getXelement(IDX::YAW);
  500. // const double vx = ekf_.getXelement(IDX::VX);
  501. // const double wz = ekf_.getXelement(IDX::WZ);
  502. // const double cov_pos_x = std::pow(pose_measure_uncertainty_time_ * vx * cos(ekf_yaw), 2.0);
  503. // const double cov_pos_y = std::pow(pose_measure_uncertainty_time_ * vx * sin(ekf_yaw), 2.0);
  504. // const double cov_yaw = std::pow(pose_measure_uncertainty_time_ * wz, 2.0);
  505. // R(0, 0) = std::pow(pose_stddev_x_, 2) + cov_pos_x; // pos_x
  506. // R(1, 1) = std::pow(pose_stddev_y_, 2) + cov_pos_y; // pos_y
  507. // R(2, 2) = std::pow(pose_stddev_yaw_, 2) + cov_yaw; // yaw
  508. // }
  509. // /* In order to avoid a large change at the time of updating, measuremeent update is performed by dividing at every
  510. // * step. */
  511. // R *= (ekf_rate_ / pose_rate_);
  512. // ekf_.updateWithDelay(y, C, R, delay_step);
  513. // // debug
  514. // Eigen::MatrixXd X_result(dim_x_, 1);
  515. // ekf_.getLatestX(X_result);
  516. // DEBUG_PRINT_MAT(X_result.transpose());
  517. // DEBUG_PRINT_MAT((X_result - X_curr).transpose());
  518. //}
  519. ///*
  520. // * measurementUpdateTwist
  521. // */
  522. //void EKFLocalizer::measurementUpdateTwist(const geometry_msgs::TwistStamped& twist)
  523. //{
  524. // if (twist.header.frame_id != "base_link")
  525. // {
  526. // ROS_WARN_DELAYED_THROTTLE(2.0, "twist frame_id must be base_link");
  527. // }
  528. // Eigen::MatrixXd X_curr(dim_x_, 1); // curent state
  529. // ekf_.getLatestX(X_curr);
  530. // DEBUG_PRINT_MAT(X_curr.transpose());
  531. // constexpr int dim_y = 2; // vx, wz
  532. // const ros::Time t_curr = ros::Time::now();
  533. // /* Calculate delay step */
  534. // double delay_time = (t_curr - twist.header.stamp).toSec() + twist_additional_delay_;
  535. // if (delay_time < 0.0)
  536. // {
  537. // ROS_WARN_DELAYED_THROTTLE(1.0, "Twist time stamp is inappropriate (delay = %f [s]), set delay to 0[s].",
  538. // delay_time);
  539. // delay_time = 0.0;
  540. // }
  541. // int delay_step = std::roundf(delay_time / ekf_dt_);
  542. // if (delay_step > extend_state_step_ - 1)
  543. // {
  544. // ROS_WARN_DELAYED_THROTTLE(1.0,
  545. // "Twist delay exceeds the compensation limit, ignored. delay: %f[s], limit = "
  546. // "extend_state_step * ekf_dt : %f [s]",
  547. // delay_time, extend_state_step_ * ekf_dt_);
  548. // return;
  549. // }
  550. // DEBUG_INFO("delay_time: %f [s]", delay_time);
  551. // /* Set measurement matrix */
  552. // Eigen::MatrixXd y(dim_y, 1);
  553. // y << twist.twist.linear.x, twist.twist.angular.z;
  554. // if (isnan(y.array()).any() || isinf(y.array()).any())
  555. // {
  556. // ROS_WARN("[EKF] twist measurement matrix includes NaN of Inf. ignore update. check twist message.");
  557. // return;
  558. // }
  559. // /* Gate */
  560. // Eigen::MatrixXd y_ekf(dim_y, 1);
  561. // y_ekf << ekf_.getXelement(delay_step * dim_x_ + IDX::VX), ekf_.getXelement(delay_step * dim_x_ + IDX::WZ);
  562. // Eigen::MatrixXd P_curr, P_y;
  563. // ekf_.getLatestP(P_curr);
  564. // P_y = P_curr.block(4, 4, dim_y, dim_y);
  565. // if (!mahalanobisGate(twist_gate_dist_, y_ekf, y, P_y))
  566. // {
  567. // ROS_WARN_DELAYED_THROTTLE(2.0, "[EKF] Twist measurement update, mahalanobis distance is over limit. ignore "
  568. // "measurement data.");
  569. // return;
  570. // }
  571. // DEBUG_PRINT_MAT(y.transpose());
  572. // DEBUG_PRINT_MAT(y_ekf.transpose());
  573. // DEBUG_PRINT_MAT((y - y_ekf).transpose());
  574. // /* Set measurement matrix */
  575. // Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim_y, dim_x_);
  576. // C(0, IDX::VX) = 1.0; // for vx
  577. // C(1, IDX::WZ) = 1.0; // for wz
  578. // /* Set measurement noise covariancs */
  579. // Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_y, dim_y);
  580. // if (use_twist_with_covariance_)
  581. // {
  582. // R(0, 0) = current_twist_covariance_.at(0); // vx - vx
  583. // R(0, 1) = current_twist_covariance_.at(5); // vx - wz
  584. // R(1, 0) = current_twist_covariance_.at(30); // wz - vx
  585. // R(1, 1) = current_twist_covariance_.at(35); // wz - wz
  586. // }
  587. // else
  588. // {
  589. // R(0, 0) = twist_stddev_vx_ * twist_stddev_vx_ * ekf_dt_; // for vx
  590. // R(1, 1) = twist_stddev_wz_ * twist_stddev_wz_ * ekf_dt_; // for wz
  591. // }
  592. // /* In order to avoid a large change by update, measurement update is performed by dividing at every step. */
  593. // R *= (ekf_rate_ / twist_rate_);
  594. // ekf_.updateWithDelay(y, C, R, delay_step);
  595. // // debug
  596. // Eigen::MatrixXd X_result(dim_x_, 1);
  597. // ekf_.getLatestX(X_result);
  598. // DEBUG_PRINT_MAT(X_result.transpose());
  599. // DEBUG_PRINT_MAT((X_result - X_curr).transpose());
  600. //};
  601. ///*
  602. // * mahalanobisGate
  603. // */
  604. bool EKFLocalizer::mahalanobisGate(const double& dist_max, const Eigen::MatrixXd& x, const Eigen::MatrixXd& obj_x,
  605. const Eigen::MatrixXd& cov)
  606. {
  607. Eigen::MatrixXd mahalanobis_squared = (x - obj_x).transpose() * cov.inverse() * (x - obj_x);
  608. DEBUG_INFO("measurement update: mahalanobis = %f, gate limit = %f", std::sqrt(mahalanobis_squared(0)), dist_max);
  609. if (mahalanobis_squared(0) > dist_max * dist_max)
  610. {
  611. mbFirst = true;
  612. return false;
  613. }
  614. return true;
  615. }
  616. ///*
  617. // * publishEstimateResult
  618. // */
  619. //void EKFLocalizer::publishEstimateResult()
  620. //{
  621. // ros::Time current_time = ros::Time::now();
  622. // Eigen::MatrixXd X(dim_x_, 1);
  623. // Eigen::MatrixXd P(dim_x_, dim_x_);
  624. // ekf_.getLatestX(X);
  625. // ekf_.getLatestP(P);
  626. // /* publish latest pose */
  627. // pub_pose_.publish(current_ekf_pose_);
  628. // /* publish latest pose with covariance */
  629. // geometry_msgs::PoseWithCovarianceStamped pose_cov;
  630. // pose_cov.header.stamp = current_time;
  631. // pose_cov.header.frame_id = current_ekf_pose_.header.frame_id;
  632. // pose_cov.pose.pose = current_ekf_pose_.pose;
  633. // pose_cov.pose.covariance[0] = P(IDX::X, IDX::X);
  634. // pose_cov.pose.covariance[1] = P(IDX::X, IDX::Y);
  635. // pose_cov.pose.covariance[5] = P(IDX::X, IDX::YAW);
  636. // pose_cov.pose.covariance[6] = P(IDX::Y, IDX::X);
  637. // pose_cov.pose.covariance[7] = P(IDX::Y, IDX::Y);
  638. // pose_cov.pose.covariance[11] = P(IDX::Y, IDX::YAW);
  639. // pose_cov.pose.covariance[30] = P(IDX::YAW, IDX::X);
  640. // pose_cov.pose.covariance[31] = P(IDX::YAW, IDX::Y);
  641. // pose_cov.pose.covariance[35] = P(IDX::YAW, IDX::YAW);
  642. // pub_pose_cov_.publish(pose_cov);
  643. // /* publish latest twist */
  644. // pub_twist_.publish(current_ekf_twist_);
  645. // /* publish latest twist with covariance */
  646. // geometry_msgs::TwistWithCovarianceStamped twist_cov;
  647. // twist_cov.header.stamp = current_time;
  648. // twist_cov.header.frame_id = current_ekf_twist_.header.frame_id;
  649. // twist_cov.twist.twist = current_ekf_twist_.twist;
  650. // twist_cov.twist.covariance[0] = P(IDX::VX, IDX::VX);
  651. // twist_cov.twist.covariance[5] = P(IDX::VX, IDX::WZ);
  652. // twist_cov.twist.covariance[30] = P(IDX::WZ, IDX::VX);
  653. // twist_cov.twist.covariance[35] = P(IDX::WZ, IDX::WZ);
  654. // pub_twist_cov_.publish(twist_cov);
  655. // /* publish yaw bias */
  656. // std_msgs::Float64 yawb;
  657. // yawb.data = X(IDX::YAWB);
  658. // pub_yaw_bias_.publish(yawb);
  659. // /* debug measured pose */
  660. // if (current_pose_ptr_ != nullptr)
  661. // {
  662. // geometry_msgs::PoseStamped p;
  663. // p = *current_pose_ptr_;
  664. // p.header.stamp = current_time;
  665. // pub_measured_pose_.publish(p);
  666. // }
  667. // /* debug publish */
  668. // double RAD2DEG = 180.0 / 3.141592;
  669. // double pose_yaw = 0.0;
  670. // if (current_pose_ptr_ != nullptr)
  671. // pose_yaw = tf2::getYaw(current_pose_ptr_->pose.orientation) * RAD2DEG;
  672. // std_msgs::Float64MultiArray msg;
  673. // msg.data.push_back(X(IDX::YAW) * RAD2DEG); // [0] ekf yaw angle
  674. // msg.data.push_back(pose_yaw); // [1] measurement yaw angle
  675. // msg.data.push_back(X(IDX::YAWB) * RAD2DEG); // [2] yaw bias
  676. // pub_debug_.publish(msg);
  677. //}
  678. double EKFLocalizer::normalizeYaw(const double& yaw)
  679. {
  680. return std::atan2(std::sin(yaw), std::cos(yaw));
  681. }
  682. void EKFLocalizer::UpdateGPS(const char *strdata, const unsigned int nSize, const unsigned int index, const QDateTime *dt, const char *strmemname)
  683. {
  684. (void )&index;
  685. (void )&dt;
  686. (void )strmemname;
  687. if(nSize<1)return;
  688. static bool bFirst = true;
  689. iv::lidar::ndtpos xndtpos;
  690. if(!xndtpos.ParseFromArray(strdata,nSize))
  691. {
  692. std::cout<<"EKFLocalizer::UpdateGPS error."<<std::endl;
  693. return;
  694. }
  695. mMutexndtpos.lock();
  696. mndtpos.CopyFrom(xndtpos);
  697. mMutexndtpos.unlock();
  698. mMutexCurPose.lock();
  699. mCurPose.x = xndtpos.pose_x();
  700. mCurPose.y = xndtpos.pose_y();
  701. mCurPose.z = xndtpos.pose_z();
  702. mCurPose.pitch = xndtpos.pose_pitch();
  703. mCurPose.roll = xndtpos.pose_roll();
  704. mCurPose.yaw = xndtpos.pose_yaw();
  705. mbCurPoseUpdate = true;
  706. mMutexCurPose.unlock();
  707. std::cout<<" ndt x: "<<mCurPose.x<<" y:"<<mCurPose.y<<std::endl;
  708. if(mbFirst == true)
  709. {
  710. Eigen::MatrixXd X(dim_x_, 1);
  711. Eigen::MatrixXd P = Eigen::MatrixXd::Zero(dim_x_, dim_x_);
  712. X(IDX::X) = mCurPose.x;
  713. X(IDX::Y) = mCurPose.y;
  714. X(IDX::YAW) = mCurPose.yaw;
  715. X(IDX::YAWB) = 0.0;
  716. X(IDX::VX) = 0.0;
  717. X(IDX::WZ) = 0.0;
  718. P(IDX::X, IDX::X) = 0;
  719. P(IDX::Y, IDX::Y) = 0;
  720. P(IDX::YAW, IDX::YAW) = 0;
  721. P(IDX::YAWB, IDX::YAWB) = 0.0001;
  722. P(IDX::VX, IDX::VX) = 0.01;
  723. P(IDX::WZ, IDX::WZ) = 0.01;
  724. ekf_.init(X, P, extend_state_step_);
  725. mbFirst = false;
  726. }
  727. mnNoData = 0;
  728. }
  729. void EKFLocalizer::measurementUpdatePose()
  730. {
  731. if(mbCurPoseUpdate == false)
  732. {
  733. return;
  734. }
  735. iv::pose xpose;
  736. mMutexCurPose.lock();
  737. xpose = mCurPose;
  738. mbCurPoseUpdate = false;
  739. mMutexCurPose.unlock();
  740. Eigen::MatrixXd X_curr(dim_x_, 1); // curent state
  741. ekf_.getLatestX(X_curr);
  742. DEBUG_PRINT_MAT(X_curr.transpose());
  743. constexpr int dim_y = 3; // pos_x, pos_y, yaw, depending on Pose output
  744. // const ros::Time t_curr = ros::Time::now();
  745. /* Calculate delay step */
  746. double delay_time =pose_additional_delay_;// (t_curr - pose.header.stamp).toSec() + pose_additional_delay_;
  747. if (delay_time < 0.0)
  748. {
  749. delay_time = 0.0;
  750. // ROS_WARN_DELAYED_THROTTLE(1.0, "Pose time stamp is inappropriate, set delay to 0[s]. delay = %f", delay_time);
  751. }
  752. int delay_step = std::roundf(delay_time / ekf_dt_);
  753. if (delay_step > extend_state_step_ - 1)
  754. {
  755. // ROS_WARN_DELAYED_THROTTLE(1.0,
  756. // "Pose delay exceeds the compensation limit, ignored. delay: %f[s], limit = "
  757. // "extend_state_step * ekf_dt : %f [s]",
  758. // delay_time, extend_state_step_ * ekf_dt_);
  759. qDebug("delay error.");
  760. return;
  761. }
  762. DEBUG_INFO("delay_time: %f [s]", delay_time);
  763. /* Set yaw */
  764. const double yaw_curr = ekf_.getXelement((unsigned int)(delay_step * dim_x_ + IDX::YAW));
  765. // double yaw = tf2::getYaw(pose.pose.orientation);
  766. double yaw = xpose.yaw;
  767. const double ekf_yaw = ekf_.getXelement(delay_step * dim_x_ + IDX::YAW);
  768. const double yaw_error = normalizeYaw(yaw - ekf_yaw); // normalize the error not to exceed 2 pi
  769. yaw = yaw_error + ekf_yaw;
  770. /* Set measurement matrix */
  771. Eigen::MatrixXd y(dim_y, 1);
  772. // y << pose.pose.position.x, pose.pose.position.y, yaw;
  773. y << xpose.x, xpose.y, yaw;
  774. if (isnan(y.array()).any() || isinf(y.array()).any())
  775. {
  776. // ROS_WARN("[EKF] pose measurement matrix includes NaN of Inf. ignore update. check pose message.");
  777. qDebug("[EKF] pose measurement matrix includes NaN of Inf. ignore update. check pose message.");
  778. return;
  779. }
  780. /* Gate */
  781. Eigen::MatrixXd y_ekf(dim_y, 1);
  782. y_ekf << ekf_.getXelement(delay_step * dim_x_ + IDX::X), ekf_.getXelement(delay_step * dim_x_ + IDX::Y), ekf_yaw;
  783. Eigen::MatrixXd P_curr, P_y;
  784. ekf_.getLatestP(P_curr);
  785. P_y = P_curr.block(0, 0, dim_y, dim_y);
  786. if (!mahalanobisGate(pose_gate_dist_, y_ekf, y, P_y))
  787. {
  788. // ROS_WARN_DELAYED_THROTTLE(2.0, "[EKF] Pose measurement update, mahalanobis distance is over limit. ignore "
  789. // "measurement data.");
  790. qDebug("[EKF] Pose measurement update, mahalanobis distance is over limit. ignore "
  791. "measurement data.");
  792. return;
  793. }
  794. DEBUG_PRINT_MAT(y.transpose());
  795. DEBUG_PRINT_MAT(y_ekf.transpose());
  796. DEBUG_PRINT_MAT((y - y_ekf).transpose());
  797. /* Set measurement matrix */
  798. Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim_y, dim_x_);
  799. C(0, IDX::X) = 1.0; // for pos x
  800. C(1, IDX::Y) = 1.0; // for pos y
  801. C(2, IDX::YAW) = 1.0; // for yaw
  802. /* Set measurement noise covariancs */
  803. Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_y, dim_y);
  804. if (use_pose_with_covariance_)
  805. {
  806. R(0, 0) = current_pose_covariance_.at(0); // x - x
  807. R(0, 1) = current_pose_covariance_.at(1); // x - y
  808. R(0, 2) = current_pose_covariance_.at(5); // x - yaw
  809. R(1, 0) = current_pose_covariance_.at(6); // y - x
  810. R(1, 1) = current_pose_covariance_.at(7); // y - y
  811. R(1, 2) = current_pose_covariance_.at(11); // y - yaw
  812. R(2, 0) = current_pose_covariance_.at(30); // yaw - x
  813. R(2, 1) = current_pose_covariance_.at(31); // yaw - y
  814. R(2, 2) = current_pose_covariance_.at(35); // yaw - yaw
  815. }
  816. else
  817. {
  818. const double ekf_yaw = ekf_.getXelement(IDX::YAW);
  819. const double vx = ekf_.getXelement(IDX::VX);
  820. const double wz = ekf_.getXelement(IDX::WZ);
  821. const double cov_pos_x = std::pow(pose_measure_uncertainty_time_ * vx * cos(ekf_yaw), 2.0);
  822. const double cov_pos_y = std::pow(pose_measure_uncertainty_time_ * vx * sin(ekf_yaw), 2.0);
  823. const double cov_yaw = std::pow(pose_measure_uncertainty_time_ * wz, 2.0);
  824. R(0, 0) = std::pow(pose_stddev_x_, 2) + cov_pos_x; // pos_x
  825. R(1, 1) = std::pow(pose_stddev_y_, 2) + cov_pos_y; // pos_y
  826. R(2, 2) = std::pow(pose_stddev_yaw_, 2) + cov_yaw; // yaw
  827. }
  828. /* In order to avoid a large change at the time of updating, measuremeent update is performed by dividing at every
  829. * step. */
  830. R *= (ekf_rate_ / pose_rate_);
  831. ekf_.updateWithDelay(y, C, R, delay_step);
  832. // debug
  833. Eigen::MatrixXd X_result(dim_x_, 1);
  834. ekf_.getLatestX(X_result);
  835. DEBUG_PRINT_MAT(X_result.transpose());
  836. DEBUG_PRINT_MAT((X_result - X_curr).transpose());
  837. }
  838. void EKFLocalizer::timerproc()
  839. {
  840. /* predict model in EKF */
  841. auto start = std::chrono::system_clock::now();
  842. DEBUG_INFO("------------------------- start prediction -------------------------");
  843. predictKinematicsModel();
  844. double elapsed =
  845. std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  846. DEBUG_INFO("[EKF] predictKinematicsModel calculation time = %f [ms]", elapsed * 1.0e-6);
  847. DEBUG_INFO("------------------------- end prediction -------------------------\n");
  848. /* pose measurement update */
  849. // if (current_pose_ptr_ != nullptr)
  850. // {
  851. DEBUG_INFO("------------------------- start Pose -------------------------");
  852. start = std::chrono::system_clock::now();
  853. measurementUpdatePose();
  854. elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  855. DEBUG_INFO("[EKF] measurementUpdatePose calculation time = %f [ms]", elapsed * 1.0e-6);
  856. DEBUG_INFO("------------------------- end Pose -------------------------\n");
  857. // }
  858. //// /* twist measurement update */
  859. //// if (current_twist_ptr_ != nullptr)
  860. //// {
  861. //// DEBUG_INFO("------------------------- start twist -------------------------");
  862. //// start = std::chrono::system_clock::now();
  863. //// measurementUpdateTwist(*current_twist_ptr_);
  864. //// elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count();
  865. //// DEBUG_INFO("[EKF] measurementUpdateTwist calculation time = %f [ms]", elapsed * 1.0e-6);
  866. //// DEBUG_INFO("------------------------- end twist -------------------------\n");
  867. //// }
  868. // /* set current pose, twist */
  869. // setCurrentResult();
  870. getcurrentpose();
  871. // /* publish ekf result */
  872. // publishEstimateResult();
  873. }
  874. void EKFLocalizer::getcurrentpose()
  875. {
  876. mekfpose.x = ekf_.getXelement(IDX::X);
  877. mekfpose.y = ekf_.getXelement(IDX::Y);
  878. mekfpose.z = 0;
  879. mekfpose.roll = 0;
  880. mekfpose.pitch = 0;
  881. double yaw = ekf_.getXelement(IDX::YAW) + ekf_.getXelement(IDX::YAWB);
  882. mekfpose.yaw = yaw;
  883. mekfpose.roll = mCurPose.roll;
  884. mekfpose.pitch = mCurPose.pitch;
  885. std::cout<<" ekf x: "<<mekfpose.x<<" y: "<<mekfpose.y<<std::endl;
  886. iv::lidar::ndtpos xndtpos;
  887. mMutexndtpos.lock();
  888. xndtpos.CopyFrom(mndtpos);
  889. mMutexndtpos.unlock();
  890. xndtpos.set_pose_x(mekfpose.x);
  891. xndtpos.set_pose_y(mekfpose.y);
  892. xndtpos.set_pose_yaw(yaw);
  893. int ndatasize = xndtpos.ByteSize();
  894. char * strdata = new char[ndatasize];
  895. if(xndtpos.SerializeToArray(strdata,ndatasize))
  896. {
  897. iv::modulecomm::ModuleSendMsg(mpandtekf,strdata,ndatasize);
  898. }
  899. delete strdata;
  900. }
  901. #include <thread>
  902. #include <QTime>
  903. void EKFLocalizer::timerthread()
  904. {
  905. const int ninterval = 10;
  906. qint64 nlastproc = 0;
  907. while(1)
  908. {
  909. if((QDateTime::currentMSecsSinceEpoch() - nlastproc)<ninterval)
  910. {
  911. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  912. continue;
  913. }
  914. nlastproc = QDateTime::currentMSecsSinceEpoch();
  915. if(mnNoData>=100)
  916. {
  917. // qDebug("continue. %d",mnNoData);
  918. continue;
  919. }
  920. timerproc();
  921. mnNoData++;
  922. }
  923. }