ceres_voxel_matcher.cc 9.36 KB
Newer Older
wangdawei's avatar
wangdawei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
#include "ceres_voxel_matcher.h"

#include <string>
#include <fstream>
#include <ceres/ceres.h>
#include <glog/logging.h>
#include "../carto/mapping/internal/3d/rotation_parameterization.h"

#include "cost_function_rotation.h"
#include "cost_function_translation.h"
#include "cost_function_voxel.h"

#define IS_CERES_MODE(x, y) ((x & y) > 0)

namespace juefx {

CeresVoxelMatcher::CeresVoxelMatcher(const CeresVoxelMatcherOption &options)
    : options_(options) {}

Eigen::Vector4d CeresVoxelMatcher::Match(const Rigid3d &init_pose,
                                         const VectorCloud &high_cloud,
                                         const VectorCloud &low_cloud,
                                         const VoxelMap &voxel_map,
                                         Rigid3d *final_pose,
                                         ceres::Solver::Summary *summary,
                                         int mode)
{
    CHECK_GT(options_.low_space_weight, 0.);
    CHECK_GT(options_.high_space_weight, 0.);
    CHECK_GT(options_.high_intensity_weight, 0.);
    CHECK_GT(options_.T_weight_xy, 0.);
    CHECK_GT(options_.T_weight_z, 0.);
    CHECK_GT(options_.R_weight_pitchroll, 0.);
    CHECK_GT(options_.R_weight_yaw, 0.);

    std::array<double, 3> translation = {init_pose.translation().x(),
                                         init_pose.translation().y(),
                                         init_pose.translation().z()};
    // Rotation quaternion as (w, x, y, z)
    // Eigen::Quaterniond init as (w, x, y, z), but stores data as (x, y, z, w)
    std::array<double, 4> rotation = {init_pose.rotation().w(), init_pose.rotation().x(),
                                      init_pose.rotation().y(), init_pose.rotation().z()};

//  options_.only_optimize_yaw()
//      ? std::unique_ptr<ceres::LocalParameterization>(
//            ceres::AutoDiffLocalParameterization(
//                cartographer::mapping::YawOnlyQuaternionPlus(), 4, 1))

    int scale = voxel_map.GetResolution(VOXEL_RESOLUTION_1X) >= 0.07 ? VOXEL_RESOLUTION_1X : VOXEL_RESOLUTION_2X;
    const InterpolatedVoxelMap high_voxel_map(voxel_map, scale);
    scale = voxel_map.GetResolution(VOXEL_RESOLUTION_1X) >= 0.07 ? VOXEL_RESOLUTION_4X : VOXEL_RESOLUTION_8X;
    const InterpolatedVoxelMap low_voxel_map(voxel_map, scale);

    ceres::Problem problem;
    ceres::Solver::Options options;
    options.linear_solver_type = ceres::DENSE_QR;
    options.num_threads = options_.threads_num;
    options.num_linear_solver_threads = options_.threads_num;

#ifndef VOXEL_MAP_CERES_DEBUG
    if (IS_CERES_MODE(mode, CERES_MODE_DEBUG))
    {
        double residual_0 = CountCloudResidual(low_cloud, low_voxel_map, init_pose, options_.low_space_weight);
        double residual_1 = CountCloudResidual(high_cloud, high_voxel_map, init_pose, options_.high_space_weight);
        printf("BEFORE ceres - high: %f low: %f", residual_1, residual_0);
    }
#else
    options.minimizer_progress_to_stdout = true;
#endif

    problem.AddParameterBlock(translation.data(), 3);
    problem.AddParameterBlock(rotation.data(), 4,
                              new ceres::QuaternionParameterization());
    problem.AddResidualBlock(
        VoxelCostFunction::CreateAutoDiffCostFunction(low_cloud, low_voxel_map, options_.low_space_weight, 0.f),
        nullptr, translation.data(), rotation.data());
    problem.AddResidualBlock(
        VoxelCostFunction::CreateAutoDiffCostFunction(high_cloud, high_voxel_map, options_.high_space_weight, 0.f),
        nullptr, translation.data(), rotation.data());
    problem.AddResidualBlock(
        TranslationDeltaCostFunction::CreateAutoDiffCostFunction(
            options_.T_weight_xy, options_.T_weight_z, init_pose.translation()),
        nullptr, translation.data());
    problem.AddResidualBlock(
        RotationDeltaCostFunction::CreateAutoDiffCostFunction(
            options_.R_weight_pitchroll, options_.R_weight_yaw, init_pose.rotation()),
        nullptr, rotation.data());
    ceres::Solve(options, &problem, summary);

#ifdef VOXEL_MAP_CERES_DEBUG
    std::cout << ">>>> " << summary->BriefReport() << std::endl;
    char buf[1024];
    Eigen::Quaterniond q(rotation[0], rotation[1], rotation[2], rotation[3]);
    Eigen::Vector3d euler3 = cartographer::transform::RotationQuaternionToEulerVector(q);
    snprintf(buf, 1023, "{ pos: %.3f %.3f %.3f, euler: %.5f %.5f %.5f }",
             translation[0], translation[1], translation[2],
             euler3.x(), euler3.y(), euler3.z());
    std::cout << ">>>> After single matching, return: " << buf << std::endl;

#endif

    *final_pose = Rigid3d(Eigen::Vector3d(translation[0], translation[1], translation[2]),
                          Eigen::Quaterniond(rotation[0], rotation[1], rotation[2], rotation[3]));

    // count loss
    double residual[4] = {0, 0, 0, 0};
    if (IS_CERES_MODE(mode, CERES_MODE_LOSS)) {
#ifndef VOXEL_MAP_CERES_DEBUG
        residual[0] = CountCloudResidual(high_cloud, high_voxel_map, *final_pose, options_.high_space_weight);
        residual[1] = CountCloudResidual(low_cloud, low_voxel_map, *final_pose, options_.low_space_weight);
#endif
        Eigen::Vector3d delta_trans = final_pose->translation() - init_pose.translation();
        Eigen::Vector3d res_trans(
            options_.T_weight_xy * delta_trans.x(),
            options_.T_weight_xy * delta_trans.y(),
            options_.T_weight_z * delta_trans.z());
        residual[2] = 0.5 * res_trans.norm() * res_trans.norm();

        Eigen::Quaterniond delta =
            init_pose.rotation().inverse() * final_pose->rotation();
        Eigen::Vector3d axis_angel =
            cartographer::transform::RotationQuaternionToAngleAxisVector(delta);
        Eigen::Vector3d res_rotat(
            options_.R_weight_pitchroll * axis_angel[0],
            options_.R_weight_pitchroll * axis_angel[1],
            options_.R_weight_yaw * axis_angel[2]);
        residual[3] = 0.5 * res_rotat.norm() * res_rotat.norm();
    }

    if (IS_CERES_MODE(mode, CERES_MODE_DEBUG)) {
        printf(" - high: %f low: %f trans: %f rotat: %f\n", 
               residual[0], residual[1], residual[2], residual[3]);
    }

    return Eigen::Vector4d(residual[0], residual[1], residual[2], residual[3]);
}

void CeresVoxelMatcher::SingleMatch(const Rigid3d &init_pose,
                                    const VectorCloud &clouds,
                                    const InterpolatedVoxelMap &voxel_map,
                                    const float space_weight,
                                    const float intensity_weight,
                                    const int max_iter_num,
                                    std::array<double, 3> &translation,
                                    std::array<double, 4> &rotation,
                                    ceres::Solver::Summary *summary) {
    ceres::Problem problem;
    ceres::Solver::Options options;
    options.linear_solver_type = ceres::DENSE_QR;
    options.num_threads = options_.threads_num;
    options.max_num_iterations = max_iter_num;
    problem.AddParameterBlock(translation.data(), 3);
    problem.AddParameterBlock(rotation.data(), 4,
                              new ceres::QuaternionParameterization());
    problem.AddResidualBlock(
        VoxelCostFunction::CreateAutoDiffCostFunction(clouds, voxel_map, space_weight, 0.f),
        nullptr, translation.data(), rotation.data());
    problem.AddResidualBlock(
        TranslationDeltaCostFunction::CreateAutoDiffCostFunction(
            options_.T_weight_xy, options_.T_weight_z, init_pose.translation()),
        nullptr, translation.data());
    problem.AddResidualBlock(
        RotationDeltaCostFunction::CreateAutoDiffCostFunction(
            options_.R_weight_pitchroll, options_.R_weight_yaw, init_pose.rotation()),
        nullptr, rotation.data());
    ceres::Solve(options, &problem, summary);

#ifdef VOXEL_MAP_CERES_DEBUG
    std::cout << ">>>> " << summary->BriefReport() << std::endl;
    char buf[1024];
    Eigen::Quaterniond q(rotation[0], rotation[1], rotation[2], rotation[3]);
    Eigen::Vector3d euler3 = cartographer::transform::RotationQuaternionToEulerVector(q);
    snprintf(buf, 1023, "{ pos: %.3f %.3f %.3f, euler: %.5f %.5f %.5f }",
             translation[0], translation[1], translation[2],
             euler3.x(), euler3.y(), euler3.z());
    std::cout << ">>>> After single matching, return: " << buf << std::endl;

#endif
}

double CeresVoxelMatcher::CountCloudResidual(const VectorCloud &clouds,
                                             const InterpolatedVoxelMap &voxel_map,
                                             const Rigid3d &trans,
                                             const float space_weight) {
    double residual = 0;
    const double scaling_factor =
        space_weight / std::sqrt(static_cast<double>(clouds.size()));
    for (size_t i = 0; i < clouds.size(); ++i)
    {
        cartographer::transform::Rigid3d::Vector point(clouds[i].x(),
                                                       clouds[i].y(),
                                                       clouds[i].z());
        const auto world = trans * point;
        double prob_space = 0., prob_intensity = 0.;
        voxel_map.GetProbability(world[0], world[1], world[2], prob_space, prob_intensity);
        DCHECK(0. <= prob_space && prob_space <= 1.);
        DCHECK(0. <= prob_intensity && prob_intensity <= 1.);
        double r = scaling_factor * (1. - prob_space);
        residual += r * r;
    }
    return 0.5 * residual;
}

}