localization_lidar_process.cc 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/localization/msf/local_integ/localization_lidar_process.h"

#include "yaml-cpp/yaml.h"

L
Liangliang Zhang 已提交
21
#include "cybertron/common/log.h"
22
#include "modules/common/time/time.h"
23
#include "modules/common/time/timer.h"
24 25 26 27 28 29 30
#include "modules/common/util/file.h"

namespace apollo {
namespace localization {
namespace msf {

using apollo::common::Status;
31
using apollo::common::time::Timer;
32 33

LocalizationLidarProcess::LocalizationLidarProcess()
34 35 36 37 38 39 40 41 42
    : locator_(new LocalizationLidar()),
      pose_forcastor_(new PoseForcast()),
      map_path_(""),
      lidar_extrinsic_file_(""),
      lidar_height_file_(""),
      localization_mode_(2),
      yaw_align_mode_(2),
      lidar_filter_size_(17),
      delta_yaw_limit_(0.25 * 3.14159 / 180.0),
43
      init_delta_yaw_limit_(1.5 * 3.14159 / 180.0),
44 45 46 47 48 49
      compensate_pitch_roll_limit_(0.035),
      utm_zone_id_(50),
      map_coverage_theshold_(0.8),
      lidar_extrinsic_(TransformD::Identity()),
      lidar_height_(),
      is_get_first_lidar_msg_(false),
50 51
      cur_predict_location_(TransformD::Identity()),
      pre_predict_location_(TransformD::Identity()),
52 53 54 55
      velocity_(Vector3D::Zero()),
      pre_location_(TransformD::Identity()),
      location_(TransformD::Identity()),
      pre_location_time_(0.0),
56 57
      location_covariance_(Matrix3D::Zero()),
      lidar_status_(LidarState::NOT_VALID),
58 59 60 61 62 63 64
      reinit_flag_(false),
      imu_lidar_max_delay_time_(0.5),
      is_unstable_reset_(true),
      unstable_count_(0),
      unstable_threshold_(0.08),
      out_map_count_(0),
      forcast_integ_state_(ForcastState::NOT_VALID),
65 66 67 68 69 70 71 72 73 74
      forcast_timer_(-1) {}

LocalizationLidarProcess::~LocalizationLidarProcess() {
  delete locator_;
  locator_ = nullptr;

  delete pose_forcastor_;
  pose_forcastor_ = nullptr;
}

75
Status LocalizationLidarProcess::Init(const LocalizationIntegParam& params) {
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  // initial_success_ = false;
  map_path_ = params.map_path;
  lidar_extrinsic_file_ = params.lidar_extrinsic_file;
  lidar_height_file_ = params.lidar_height_file;
  localization_mode_ = params.localization_mode;
  yaw_align_mode_ = params.lidar_yaw_align_mode;
  utm_zone_id_ = params.utm_zone_id;
  map_coverage_theshold_ = params.map_coverage_theshold;
  imu_lidar_max_delay_time_ = params.imu_lidar_max_delay_time;

  lidar_filter_size_ = params.lidar_filter_size;

  is_unstable_reset_ = params.is_lidar_unstable_reset;
  unstable_threshold_ = params.unstable_reset_threshold;

  lidar_status_ = LidarState::NOT_VALID;

  // reload_map_flag_ = false;
  reinit_flag_ = false;

  // buffer
  out_map_count_ = 0;

  is_get_first_lidar_msg_ = false;
  cur_predict_location_ = TransformD::Identity();
  pre_predict_location_ = TransformD::Identity();
  pre_location_ = TransformD::Identity();
  velocity_ = Vector3D::Zero();
  location_ = TransformD::Identity();
  location_covariance_ = Matrix3D::Zero();

  bool sucess = LoadLidarExtrinsic(lidar_extrinsic_file_, &lidar_extrinsic_);
  if (!sucess) {
    AERROR << "LocalizationLidar: Fail to access the lidar"
110 111
              " extrinsic file: "
           << lidar_extrinsic_file_;
112
    return Status(common::LOCALIZATION_ERROR_LIDAR,
113
                  "Fail to access the lidar extrinsic file");
114 115 116 117 118
  }

  sucess = LoadLidarHeight(lidar_height_file_, &lidar_height_);
  if (!sucess) {
    AWARN << "LocalizationLidar: Fail to load the lidar"
119 120
             " height file: "
          << lidar_height_file_ << " Will use default value!";
121 122 123
    lidar_height_.height = params.lidar_height_default;
  }

124 125
  if (!locator_->Init(map_path_, lidar_filter_size_, lidar_filter_size_,
                      utm_zone_id_)) {
126
    return Status(common::LOCALIZATION_ERROR_LIDAR,
127
                  "Fail to load localization map!");
128 129 130 131 132 133 134 135 136 137 138
  }

  locator_->SetVelodyneExtrinsic(lidar_extrinsic_);
  locator_->SetLocalizationMode(localization_mode_);
  locator_->SetImageAlignMode(yaw_align_mode_);
  locator_->SetValidThreshold(map_coverage_theshold_);
  locator_->SetVehicleHeight(lidar_height_.height);
  locator_->SetDeltaPitchRollLimit(compensate_pitch_roll_limit_);

  const double deg_to_rad = 0.017453292519943;
  const double max_gyro_input = 200 * deg_to_rad;  // 200 degree
139
  const double max_acc_input = 5.0;                // 5.0 m/s^2
140 141 142 143 144 145 146 147 148
  pose_forcastor_->SetMaxListNum(400);
  pose_forcastor_->SetMaxAccelInput(max_acc_input);
  pose_forcastor_->SetMaxGyroInput(max_gyro_input);
  pose_forcastor_->SetZoneId(utm_zone_id_);

  return Status::OK();
}

double LocalizationLidarProcess::ComputeDeltaYawLimit(
149 150
    const int64_t index_cur, const int64_t index_stable, const double limit_min,
    const double limit_max) {
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  if (index_cur > index_stable) {
    return limit_min;
  }

  double ratio = static_cast<double>(index_cur);
  ratio /= static_cast<double>(index_stable);
  return limit_min * ratio + limit_max * (1.0 - ratio);
}

void LocalizationLidarProcess::PcdProcess(const LidarFrame& lidar_frame) {
  if (!CheckState()) {
    AERROR << "PcdProcess: Receive an invalid lidar msg!";
    return;
  }

  // pcd process cost time
  Timer timer;
  timer.Start();

  static unsigned int pcd_index = 0;

172
  if (!GetPredictPose(lidar_frame.measurement_time, &cur_predict_location_,
173 174 175 176 177 178 179
                      &forcast_integ_state_)) {
    AINFO << "PcdProcess: Discard a lidar msg because can't get predict pose. "
          << "More info see log in function GetPredictPose.";
    return;
  }

  if (forcast_integ_state_ != ForcastState::INCREMENT) {
180
    forcast_timer_ = -1;
181 182 183
  }
  ++forcast_timer_;

184 185
  locator_->SetDeltaYawLimit(ComputeDeltaYawLimit(
      forcast_timer_, 10, delta_yaw_limit_, init_delta_yaw_limit_));
186 187 188 189 190 191 192 193

  if (!is_get_first_lidar_msg_) {
    pre_predict_location_ = cur_predict_location_;
    pre_location_ = cur_predict_location_;
    velocity_ = Vector3D::Zero();
    is_get_first_lidar_msg_ = true;
  }

194
  velocity_ = cur_predict_location_.translation() - pre_location_.translation();
195

196 197
  int ret = locator_->Update(pcd_index++, cur_predict_location_, velocity_,
                             lidar_frame);
198 199 200 201 202 203

  UpdateState(ret, lidar_frame.measurement_time);

  timer.End("Lidar process");
}

204 205 206
void LocalizationLidarProcess::GetResult(int* lidar_status,
                                         TransformD* location,
                                         Matrix3D* covariance) const {
207 208 209 210 211 212 213 214 215 216
  CHECK_NOTNULL(lidar_status);
  CHECK_NOTNULL(location);
  CHECK_NOTNULL(covariance);

  *lidar_status = static_cast<int>(lidar_status_);
  *location = location_;
  *covariance = location_covariance_;
  return;
}

217
int LocalizationLidarProcess::GetResult(LocalizationEstimate* lidar_local_msg) {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  if (lidar_local_msg == nullptr) {
    return static_cast<int>(LidarState::NOT_VALID);
  }

  lidar_local_msg->set_measurement_time(pre_location_time_);

  apollo::common::Header* headerpb = lidar_local_msg->mutable_header();
  headerpb->set_timestamp_sec(pre_location_time_);

  apollo::localization::Pose* posepb = lidar_local_msg->mutable_pose();
  apollo::common::PointENU* position = posepb->mutable_position();
  position->set_x(location_.translation()(0));
  position->set_y(location_.translation()(1));
  position->set_z(location_.translation()(2));

  apollo::common::Quaternion* quaternion = posepb->mutable_orientation();
  Eigen::Quaterniond quat(location_.linear());
  quaternion->set_qx(quat.x());
  quaternion->set_qy(quat.y());
  quaternion->set_qz(quat.z());
  quaternion->set_qw(quat.w());

  apollo::localization::Uncertainty* uncertainty =
      lidar_local_msg->mutable_uncertainty();

  apollo::common::Point3D* position_std_dev =
      uncertainty->mutable_position_std_dev();
  position_std_dev->set_x(location_covariance_(0, 0));
  position_std_dev->set_y(location_covariance_(1, 1));
  position_std_dev->set_z(0.0);

  constexpr double yaw_covariance = 0.15 * 0.15 * DEG_TO_RAD2;
  apollo::common::Point3D* orientation_std_dev =
      uncertainty->mutable_orientation_std_dev();
  orientation_std_dev->set_x(0.0);
  orientation_std_dev->set_y(0.0);
  orientation_std_dev->set_z(yaw_covariance);

  return static_cast<int>(lidar_status_);
}

259
void LocalizationLidarProcess::IntegPvaProcess(const InsPva& sins_pva_msg) {
260 261 262 263 264 265 266 267 268 269
  pose_forcastor_->PushInspvaData(sins_pva_msg);
  return;
}

void LocalizationLidarProcess::RawImuProcess(const ImuData& imu_msg) {
  pose_forcastor_->PushImuData(imu_msg);
  return;
}

bool LocalizationLidarProcess::GetPredictPose(const double lidar_time,
270 271
                                              TransformD* predict_pose,
                                              ForcastState* forcast_state) {
272 273 274 275 276
  CHECK_NOTNULL(predict_pose);
  CHECK_NOTNULL(forcast_state);

  double latest_imu_time = pose_forcastor_->GetLastestImuTime();
  if (latest_imu_time - lidar_time > imu_lidar_max_delay_time_) {
277 278 279 280
    AERROR << std::setprecision(16) << "LocalizationLidar GetPredictPose: "
           << "Lidar msg too old! "
           << "lidar time: " << lidar_time
           << "delay time: " << latest_imu_time - lidar_time;
281 282 283 284 285 286 287
    return false;
  }

  Pose forcast_pose;
  int state = -1;
  if (lidar_status_ != LidarState::OK) {
    Pose init_pose;
288 289
    state = pose_forcastor_->GetBestForcastPose(lidar_time, -1, init_pose,
                                                &forcast_pose);
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  } else {
    Pose init_pose;
    init_pose.x = pre_location_.translation()(0);
    init_pose.y = pre_location_.translation()(1);
    init_pose.z = pre_location_.translation()(2);
    Eigen::Quaterniond quatd(pre_location_.linear());
    init_pose.qx = quatd.x();
    init_pose.qy = quatd.y();
    init_pose.qz = quatd.z();
    init_pose.qw = quatd.w();

    state = pose_forcastor_->GetBestForcastPose(lidar_time, pre_location_time_,
                                                init_pose, &forcast_pose);
  }

  if (state < 0) {
    AINFO << "LocalizationLidar GetPredictPose: "
307
          << "Recive a lidar msg, but can't query predict pose.";
308 309 310 311
    *forcast_state = ForcastState::NOT_VALID;
    return false;
  }

312
  if (std::abs(forcast_pose.x) < 10.0 || std::abs(forcast_pose.y) < 10.0) {
313 314 315 316
    AERROR << "LocalizationLidar Fatal Error: invalid pose!";
    return false;
  }

317 318
  Eigen::Quaterniond quatd(forcast_pose.qw, forcast_pose.qx, forcast_pose.qy,
                           forcast_pose.qz);
319 320 321 322 323 324 325 326
  Eigen::Translation3d transd(
      Eigen::Vector3d(forcast_pose.x, forcast_pose.y, forcast_pose.z));
  *predict_pose = transd * quatd;

  if (state == 0) {
    *forcast_state = ForcastState::INITIAL;
  } else {
    *forcast_state = ForcastState::INCREMENT;
327 328
    AINFO << "The delta translation input lidar localization: " << lidar_time
          << " " << forcast_pose.x - pre_location_.translation()(0) << " "
329 330 331 332 333 334 335
          << forcast_pose.y - pre_location_.translation()(1) << " "
          << forcast_pose.z - pre_location_.translation()(2);
  }

  return true;
}

336
bool LocalizationLidarProcess::CheckState() { return true; }
337 338 339 340 341 342 343

void LocalizationLidarProcess::UpdateState(const int ret, const double time) {
  if (ret == 0) {  // OK
    locator_->GetResult(&location_, &location_covariance_);
    lidar_status_ = LidarState::OK;

    // check covariance
344 345
    double cur_location_std_area = std::sqrt(location_covariance_(0, 0)) *
                                   std::sqrt(location_covariance_(1, 1));
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    if (cur_location_std_area > unstable_threshold_) {
      ++unstable_count_;
    } else {
      unstable_count_ = 0;
    }

    // check if lidar need reset
    if (unstable_count_ >= 2 && is_unstable_reset_) {
      unstable_count_ = 2;
      reinit_flag_ = true;
      AWARN << "Reinit lidar localization due to big covariance";
      lidar_status_ = LidarState::NOT_STABLE;
    } else {
      lidar_status_ = LidarState::OK;
      if (out_map_count_ > 0) {
        --out_map_count_;
      }
    }
    pre_location_ = location_;
    pre_location_time_ = time;

  } else if (ret == -2) {  // out of map
    locator_->GetResult(&location_, &location_covariance_);
    lidar_status_ = LidarState::NOT_STABLE;
    pre_location_ = location_;
    pre_location_time_ = time;
    if (out_map_count_ < 10) {
      ++out_map_count_;
    } else {
      reinit_flag_ = true;
    }
  } else {  // NOT_VALID
    AERROR << "LocalizationLidar: The reflection map load failed!";
    lidar_status_ = LidarState::NOT_VALID;
  }
}

383 384
bool LocalizationLidarProcess::LoadLidarExtrinsic(const std::string& file_path,
                                                  TransformD* lidar_extrinsic) {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  CHECK_NOTNULL(lidar_extrinsic);

  YAML::Node config = YAML::LoadFile(file_path);
  if (config["transform"]) {
    if (config["transform"]["translation"]) {
      lidar_extrinsic->translation()(0) =
          config["transform"]["translation"]["x"].as<double>();
      lidar_extrinsic->translation()(1) =
          config["transform"]["translation"]["y"].as<double>();
      lidar_extrinsic->translation()(2) =
          config["transform"]["translation"]["z"].as<double>();
      if (config["transform"]["rotation"]) {
        double qx = config["transform"]["rotation"]["x"].as<double>();
        double qy = config["transform"]["rotation"]["y"].as<double>();
        double qz = config["transform"]["rotation"]["z"].as<double>();
        double qw = config["transform"]["rotation"]["w"].as<double>();
        lidar_extrinsic->linear() =
            Eigen::Quaterniond(qw, qx, qy, qz).toRotationMatrix();
        return true;
      }
    }
  }
  return false;
}

bool LocalizationLidarProcess::LoadLidarHeight(const std::string& file_path,
411
                                               LidarHeight* height) {
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  CHECK_NOTNULL(height);

  if (!common::util::PathExists(file_path)) {
    return false;
  }

  YAML::Node config = YAML::LoadFile(file_path);
  if (config["vehicle"]) {
    if (config["vehicle"]["parameters"]) {
      height->height = config["vehicle"]["parameters"]["height"].as<double>();
      height->height_var =
          config["vehicle"]["parameters"]["height_var"].as<double>();
      return true;
    }
  }
  return false;
}

}  // namespace msf
}  // namespace localization
}  // namespace apollo