Bladeren bron

first commit

Lenotary 3 jaren geleden
commit
94560d642f

+ 88 - 0
CMakeLists.txt

@@ -0,0 +1,88 @@
+#############################################################
+#                                                           #
+# Copyright (c) 2021, University of California, Los Angeles #
+#                                                           #
+# Authors: Kenny J. Chen, Brett T. Lopez                    #
+# Contact: kennyjchen@ucla.edu, btlopez@ucla.edu            #
+#                                                           #
+#############################################################
+
+cmake_minimum_required(VERSION 3.10.0)
+project(direct_lidar_odometry)
+
+add_compile_options(-std=c++14)
+set(CMAKE_BUILD_TYPE "Release")
+
+find_package( PCL REQUIRED )
+include_directories(${PCL_INCLUDE_DIRS})
+add_definitions(${PCL_DEFINITIONS})
+link_directories(${PCL_LIBRARY_DIRS})
+
+find_package( Eigen3 REQUIRED )
+include_directories(${EIGEN3_INCLUDE_DIR})
+
+include(FindOpenMP)
+if(OPENMP_FOUND)
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
+else(OPENMP_FOUND)
+  message("ERROR: OpenMP could not be found.")
+endif(OPENMP_FOUND)
+
+set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
+set(THREADS_PREFER_PTHREAD_FLAG TRUE)
+find_package(Threads REQUIRED)
+
+find_package(catkin REQUIRED COMPONENTS
+  roscpp
+  std_msgs
+  sensor_msgs
+  geometry_msgs
+  pcl_ros
+)
+
+catkin_package(
+  CATKIN_DEPENDS
+    roscpp
+    std_msgs
+    sensor_msgs
+    geometry_msgs
+    pcl_ros
+  INCLUDE_DIRS
+    include
+  LIBRARIES
+    ${PROJECT_NAME}
+    nano_gicp
+    nanoflann
+)
+
+include_directories(include ${catkin_INCLUDE_DIRS})
+
+# NanoFLANN
+add_library(nanoflann SHARED
+  src/nano_gicp/nanoflann.cc
+)
+target_link_libraries(nanoflann ${PCL_LIBRARIES})
+target_include_directories(nanoflann PUBLIC include ${PCL_INCLUDE_DIRS})
+
+# NanoGICP
+add_library(nano_gicp SHARED
+  src/nano_gicp/lsq_registration.cc
+  src/nano_gicp/nano_gicp.cc
+)
+target_link_libraries(nano_gicp ${PCL_LIBRARIES} ${OpenMP_LIBS} nanoflann)
+target_include_directories(nano_gicp PUBLIC include ${PCL_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR})
+
+# Odometry Node
+add_executable(dlo_odom_node src/dlo/odom_node.cc src/dlo/odom.cc)
+add_dependencies(dlo_odom_node ${catkin_EXPORTED_TARGETS})
+target_compile_options(dlo_odom_node PRIVATE ${OpenMP_FLAGS})
+target_link_libraries(dlo_odom_node ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenMP_LIBS} Threads::Threads nano_gicp)
+
+# Mapping Node
+add_executable (dlo_map_node src/dlo/map_node.cc src/dlo/map.cc)
+add_dependencies(dlo_map_node ${catkin_EXPORTED_TARGETS})
+target_compile_options(dlo_map_node PRIVATE ${OpenMP_FLAGS})
+target_link_libraries(dlo_map_node ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenMP_LIBS} Threads::Threads)
+

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Kenny J. Chen, Brett T. Lopez
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 108 - 0
README.md

@@ -0,0 +1,108 @@
+# Direct LiDAR Odometry: Fast Localization with Dense Point Clouds
+
+[DLO](https://arxiv.org/abs/2110.00605) is a lightweight and computationally-efficient frontend LiDAR odometry solution with consistent and accurate localization. It features several algorithmic innovations that increase speed, accuracy, and robustness of pose estimation in perceptually-challenging environments and has been extensively tested on aerial and legged robots.
+
+This work was part of NASA JPL Team CoSTAR's research and development efforts for the DARPA Subterranean Challenge, in which DLO was the primary state estimation component for our fleet of autonomous aerial vehicles.
+
+<br>
+<p align='center'>
+    <img src="./doc/img/aquila.png" alt="drawing" width="320"/>
+    <img src="./doc/img/spot.png" alt="drawing" width="320"/>
+</p>
+<p align="center">
+    <img src="./doc/gif/dlo.gif" alt="drawing" width="720"/>
+</p>
+
+## Instructions
+DLO requires an input point cloud of type `sensor_msgs::PointCloud2` with an optional IMU input of type `sensor_msgs::Imu`. Note that although IMU data is not required, it can be used for initial gravity alignment and will help with point cloud registration.
+
+### Dependencies
+Our system has been tested extensively on both Ubuntu 18.04 Bionic with ROS Melodic and Ubuntu 20.04 Focal with ROS Noetic, although other versions may work. The following configuration with required dependencies has been verified to be compatible:
+
+- Ubuntu 18.04 or 20.04
+- ROS Melodic or Noetic (`roscpp`, `std_msgs`, `sensor_msgs`, `geometry_msgs`, `pcl_ros`)
+- C++ 14
+- CMake >= `3.16.3`
+- OpenMP >= `4.5`
+- Point Cloud Library >= `1.10.0`
+- Eigen >= `3.3.7`
+
+Installing the binaries from Aptitude should work though:
+```
+sudo apt install libomp-dev libpcl-dev libeigen3-dev 
+```
+
+### Compiling
+Create a catkin workspace, clone the `direct_lidar_odometry` repository into the `src` folder, and compile via the [`catkin_tools`](https://catkin-tools.readthedocs.io/en/latest/) package (or [`catkin_make`](http://wiki.ros.org/catkin/commands/catkin_make) if preferred):
+```
+mkdir ws && cd ws && mkdir src && catkin init && cd src
+git clone https://github.com/vectr-ucla/direct_lidar_odometry.git
+catkin build
+```
+
+### Execution
+After sourcing the workspace, launch the DLO odometry and mapping ROS nodes via:
+
+```
+roslaunch direct_lidar_odometry dlo.launch \
+  pointcloud_topic:=/robot/velodyne_points \
+  imu_topic:=/robot/vn100/imu
+```
+
+Make sure to edit the `pointcloud_topic` and `imu_topic` input arguments with your specific topics. If an IMU is not being used, set the `dlo/imu` ROS param to `false` in `cfg/dlo.yaml`. However, if IMU data is available, please allow DLO to calibrate and gravity align for three seconds before moving. Note that the current implementation assumes that LiDAR and IMU coordinate frames coincide, so please make sure that the sensors are physically mounted near each other.
+
+If successful, RViz will open and you will see similar terminal outputs to the following:
+
+<p align='center'>
+    <img src="./doc/img/imu_calibration.png" alt="drawing" width="400"/>
+    <img src="./doc/img/terminal_output.png" alt="drawing" width="400"/>
+</p>
+
+### Test Data
+For your convenience, we provide example test data [here](https://ucla.box.com/shared/static/ziojd3auzp0zzcgwb1ucau9anh69xwv9.bag) (9 minutes, ~4.2GB). To run, first launch DLO (with default point cloud and IMU topics) via:
+
+```
+roslaunch direct_lidar_odometry dlo.launch
+```
+
+In a separate terminal session, play back the downloaded bag:
+
+```
+rosbag play dlo_test.bag
+```
+
+<p align='center'>
+    <img src="./doc/img/test_map.png" alt="drawing" width="640"/>
+</p>
+
+## Citation
+If you found this work useful, please cite our manuscript:
+
+```
+@article{chen2021direct,
+  title={Direct LiDAR Odometry: Fast Localization with Dense Point Clouds},
+  author={Chen, Kenny and Lopez, Brett T and Agha-mohammadi, Ali-akbar and Mehta, Ankur},
+  journal={arXiv preprint arXiv:2110.00605},
+  year={2021}
+}
+```
+
+## Acknowledgements
+
+We thank the authors of the [FastGICP](https://github.com/SMRT-AIST/fast_gicp) and [NanoFLANN](https://github.com/jlblancoc/nanoflann) open-source packages:
+
+- Kenji Koide, Masashi Yokozuka, Shuji Oishi, and Atsuhiko Banno, “Voxelized GICP for Fast and Accurate 3D Point Cloud Registration,” in _IEEE International Conference on Robotics and Automation (ICRA)_, IEEE, 2021, pp. 11 054–11 059.
+- Jose Luis Blanco and Pranjal Kumar Rai, “NanoFLANN: a C++ Header-Only Fork of FLANN, A Library for Nearest Neighbor (NN) with KD-Trees,” https://github.com/jlblancoc/nanoflann, 2014.
+
+## License
+This work is licensed under the terms of the MIT license.
+
+<br>
+<p align='center'>
+    <img src="./doc/img/mc_topdown.png" alt="drawing" height="220"/>
+    <img src="./doc/img/mc_entrance.png" alt="drawing" height="220"/>
+</p>
+<p align="center">
+    <img src="./doc/gif/aquila.gif" alt="drawing" width="720"/>
+    <img src="./doc/gif/spot.gif" alt="drawing" width="720"/>
+</p>

+ 28 - 0
cfg/dlo.yaml

@@ -0,0 +1,28 @@
+#############################################################
+#                                                           #
+# Copyright (c) 2021, University of California, Los Angeles #
+#                                                           #
+# Authors: Kenny J. Chen, Brett T. Lopez                    #
+# Contact: kennyjchen@ucla.edu, btlopez@ucla.edu            #/home/lenotary/.leetcode/1.两数之和.py
+#                                                           #
+#############################################################
+
+dlo:
+
+  version: 1.0.0
+
+  adaptiveParams: true
+
+  imu: true
+  gravityAlign: true
+
+  odomNode:
+    odom_frame: odom
+    child_frame: rslidar
+    extrinsicTrans: [ 0.0, 0.0, 0.0 ]
+    extrinsicRot: [ 0, -1, 0, 1, 0, 0, 0, 0, 1 ]
+    extrinsicRPY: [ 0, -1, 0, 1, 0, 0, 0, 0, 1 ]
+
+  mapNode:
+    publishFreq: 1.0
+    leafSize: 0.25

+ 59 - 0
cfg/params.yaml

@@ -0,0 +1,59 @@
+#############################################################
+#                                                           #
+# Copyright (c) 2021, University of California, Los Angeles #
+#                                                           #
+# Authors: Kenny J. Chen, Brett T. Lopez                    #
+# Contact: kennyjchen@ucla.edu, btlopez@ucla.edu            #
+#                                                           #
+#############################################################
+
+dlo:
+
+  odomNode:
+
+    preprocessing:
+      cropBoxFilter:
+        use: true
+        size: 1.0
+      voxelFilter:
+        scan:
+          use: true
+          res: 0.25
+        submap:
+          use: true
+          res: 0.5
+
+    keyframe:
+      threshD: 5.0
+      threshR: 45.0
+
+    submap:
+      keyframe:
+        knn: 10
+        kcv: 10
+        kcc: 10
+
+    imu:
+      calibTime: 3
+      bufferSize: 2000
+
+    gicp:
+      minNumPoints: 10
+      s2s:
+        kCorrespondences: 10
+        maxCorrespondenceDistance: 1.0
+        maxIterations: 32
+        transformationEpsilon: 0.01
+        euclideanFitnessEpsilon: 0.01
+        ransac:
+          iterations: 5
+          outlierRejectionThresh: 1.0
+      s2m:
+        kCorrespondences: 20
+        maxCorrespondenceDistance: 0.5
+        maxIterations: 32
+        transformationEpsilon: 0.01
+        euclideanFitnessEpsilon: 0.01
+        ransac:
+          iterations: 5
+          outlierRejectionThresh: 1.0

BIN
doc/gif/aquila.gif


BIN
doc/gif/dlo.gif


BIN
doc/gif/keyframes.gif


BIN
doc/gif/spot.gif


BIN
doc/img/aquila.png


BIN
doc/img/imu_calibration.png


BIN
doc/img/mc_entrance.png


BIN
doc/img/mc_topdown.png


BIN
doc/img/spot.png


BIN
doc/img/terminal_output.png


BIN
doc/img/test_map.png


+ 57 - 0
include/dlo/dlo.h

@@ -0,0 +1,57 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include <atomic>
+#include <cpuid.h>
+#include <fstream>
+#include <iomanip>
+#include <ios>
+#include <iostream>
+#include <mutex>
+#include <signal.h>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+#include <sys/times.h>
+#include <sys/vtimes.h>
+#include <thread>
+
+#include <ros/ros.h>
+#include <boost/circular_buffer.hpp>
+#include <boost/algorithm/string.hpp>
+
+#include <pcl/filters/crop_box.h>
+#include <pcl/filters/voxel_grid.h>
+#include <pcl/io/pcd_io.h>
+#include <pcl/surface/concave_hull.h>
+#include <pcl/surface/convex_hull.h>
+#include <pcl_conversions/pcl_conversions.h>
+#include <pcl_ros/impl/transforms.hpp>
+#include <pcl_ros/point_cloud.h>
+#include <pcl_ros/transforms.h>
+#include <tf2_ros/transform_broadcaster.h>
+
+#include <geometry_msgs/PoseStamped.h>
+#include <nav_msgs/Odometry.h>
+#include <sensor_msgs/CameraInfo.h>
+#include <sensor_msgs/Image.h>
+#include <sensor_msgs/Imu.h>
+#include <sensor_msgs/PointCloud2.h>
+
+#include <nano_gicp/nano_gicp.hpp>
+
+typedef pcl::PointXYZI PointType;
+
+namespace dlo {
+
+  class OdomNode;
+  class MapNode;
+
+}

+ 53 - 0
include/dlo/map.h

@@ -0,0 +1,53 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/dlo.h"
+
+class dlo::MapNode {
+
+public:
+
+  MapNode(ros::NodeHandle node_handle);
+  ~MapNode();
+
+  static void abort() {
+    abort_ = true;
+  }
+
+  void start();
+  void stop();
+
+private:
+
+  void abortTimerCB(const ros::TimerEvent& e);
+  void publishTimerCB(const ros::TimerEvent& e);
+
+  void keyframeCB(const sensor_msgs::PointCloud2ConstPtr& keyframe);
+
+  void getParams();
+
+  ros::NodeHandle nh;
+  ros::Timer abort_timer;
+  ros::Timer publish_timer;
+
+  ros::Subscriber keyframe_sub;
+  ros::Publisher map_pub;
+
+  pcl::PointCloud<PointType>::Ptr dlo_map;
+  pcl::VoxelGrid<PointType> voxelgrid;
+
+  ros::Time map_stamp;
+  std::string odom_frame;
+
+  double publish_freq_;
+  double leaf_size_;
+
+  static std::atomic<bool> abort_;
+
+};

+ 245 - 0
include/dlo/odom.h

@@ -0,0 +1,245 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/dlo.h"
+
+class dlo::OdomNode {
+
+public:
+
+  OdomNode(ros::NodeHandle node_handle);
+  ~OdomNode();
+
+  static void abort() {
+    abort_ = true;
+  }
+
+  void start();
+  void stop();
+
+private:
+
+  void abortTimerCB(const ros::TimerEvent& e);
+  void icpCB(const sensor_msgs::PointCloud2ConstPtr& pc);
+  void imuCB(const sensor_msgs::Imu::ConstPtr& imu);
+  sensor_msgs::Imu imuConverter(const sensor_msgs::Imu& imu_in);
+
+  void getParams();
+
+  void publishToROS();
+  void publishPose();
+  void publishTransform();
+  void publishKeyframe();
+
+  void preprocessPoints();
+  void initializeInputTarget();
+  void setInputSources();
+
+  void initializeDLO();
+  void gravityAlign();
+
+  void getNextPose();
+  void integrateIMU();
+
+  void propagateS2S(Eigen::Matrix4f T);
+  void propagateS2M();
+
+  void setAdaptiveParams();
+
+  void computeMetrics();
+  void computeSpaciousness();
+
+  void transformCurrentScan();
+  void updateKeyframes();
+  void computeConvexHull();
+  void computeConcaveHull();
+  void pushSubmapIndices(std::vector<float> dists, int k);
+  void getSubmapKeyframes();
+
+  void debug();
+
+  double first_imu_time;
+
+  ros::NodeHandle nh;
+  ros::Timer abort_timer;
+
+  ros::Subscriber icp_sub;
+  ros::Subscriber imu_sub;
+
+  ros::Publisher odom_pub;
+  ros::Publisher keyframe_pub;
+  ros::Publisher kf_pub;
+
+  std::vector<std::pair<Eigen::Vector3f, Eigen::Quaternionf>> trajectory;
+  std::vector<std::pair<std::pair<Eigen::Vector3f, Eigen::Quaternionf>, pcl::PointCloud<PointType>::Ptr>> keyframes;
+  std::vector<std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>> keyframe_normals;
+
+  std::atomic<bool> dlo_initialized;
+  std::atomic<bool> imu_calibrated;
+  std::atomic<bool> normals_initialized;
+
+  std::string odom_frame;
+  std::string child_frame;
+    Eigen::Matrix3d extRot;
+    Eigen::Matrix3d extRPY;
+    Eigen::Vector3d extTrans;
+    Eigen::Quaterniond extQRPY;
+  pcl::PointCloud<PointType>::Ptr original_scan;
+  pcl::PointCloud<PointType>::Ptr current_scan;
+  pcl::PointCloud<PointType>::Ptr current_scan_t;
+
+  pcl::PointCloud<PointType>::Ptr keyframes_cloud;
+  pcl::PointCloud<PointType>::Ptr keyframe_cloud;
+  int num_keyframes;
+
+  pcl::ConvexHull<PointType> convex_hull;
+  pcl::ConcaveHull<PointType> concave_hull;
+  std::vector<int> keyframe_convex;
+  std::vector<int> keyframe_concave;
+
+  pcl::PointCloud<PointType>::Ptr submap_cloud;
+  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> submap_normals;
+
+  std::vector<int> submap_kf_idx_curr;
+  std::vector<int> submap_kf_idx_prev;
+  std::atomic<bool> submap_hasChanged;
+
+  pcl::PointCloud<PointType>::Ptr source_cloud;
+  pcl::PointCloud<PointType>::Ptr target_cloud;
+
+  ros::Time scan_stamp;
+
+  double curr_frame_stamp;
+  double prev_frame_stamp;
+  std::vector<double> comp_times;
+
+  nano_gicp::NanoGICP<PointType, PointType> gicp_s2s;
+  nano_gicp::NanoGICP<PointType, PointType> gicp;
+
+  pcl::CropBox<PointType> crop;
+  pcl::VoxelGrid<PointType> vf_scan;
+  pcl::VoxelGrid<PointType> vf_submap;
+
+  nav_msgs::Odometry odom;
+  nav_msgs::Odometry kf;
+
+  geometry_msgs::PoseStamped pose_ros;
+
+  Eigen::Matrix4f T;
+  Eigen::Matrix4f T_s2s, T_s2s_prev;
+  Eigen::Quaternionf q_final;
+
+  Eigen::Vector3f pose_s2s;
+  Eigen::Matrix3f rotSO3_s2s;
+  Eigen::Quaternionf rotq_s2s;
+
+  Eigen::Vector3f pose;
+  Eigen::Matrix3f rotSO3;
+  Eigen::Quaternionf rotq;
+
+  Eigen::Matrix4f imu_SE3;
+
+  struct XYZd {
+    double x;
+    double y;
+    double z;
+  };
+
+  struct ImuBias {
+    XYZd gyro;
+    XYZd accel;
+  };
+
+  ImuBias imu_bias;
+
+  struct ImuMeas {
+    double stamp;
+    XYZd ang_vel;
+    XYZd lin_accel;
+  };
+
+  ImuMeas imu_meas;
+
+  boost::circular_buffer<ImuMeas> imu_buffer;
+
+  static bool comparatorImu(ImuMeas m1, ImuMeas m2) {
+    return (m1.stamp < m2.stamp);
+  };
+
+  struct Metrics {
+    std::vector<float> spaciousness;
+  };
+
+  Metrics metrics;
+
+  static std::atomic<bool> abort_;
+  std::atomic<bool> stop_publish_thread;
+  std::atomic<bool> stop_publish_keyframe_thread;
+  std::atomic<bool> stop_metrics_thread;
+  std::atomic<bool> stop_debug_thread;
+
+  std::thread publish_thread;
+  std::thread publish_keyframe_thread;
+  std::thread metrics_thread;
+  std::thread debug_thread;
+
+  std::mutex mtx_imu;
+
+  std::string cpu_type;
+  std::vector<double> cpu_percents;
+  clock_t lastCPU, lastSysCPU, lastUserCPU;
+  int numProcessors;
+
+  // Parameters
+  std::string version_;
+
+  bool gravity_align_;
+
+  double keyframe_thresh_dist_;
+  double keyframe_thresh_rot_;
+
+  int submap_knn_;
+  int submap_kcv_;
+  int submap_kcc_;
+  double submap_concave_alpha_;
+
+  bool crop_use_;
+  double crop_size_;
+
+  bool vf_scan_use_;
+  double vf_scan_res_;
+
+  bool vf_submap_use_;
+  double vf_submap_res_;
+
+  bool adaptive_params_use_;
+
+  bool imu_use_;
+  int imu_calib_time_;
+  int imu_buffer_size_;
+
+  int gicp_min_num_points_;
+
+  int gicps2s_k_correspondences_;
+  double gicps2s_max_corr_dist_;
+  int gicps2s_max_iter_;
+  double gicps2s_transformation_ep_;
+  double gicps2s_euclidean_fitness_ep_;
+  int gicps2s_ransac_iter_;
+  double gicps2s_ransac_inlier_thresh_;
+
+  int gicps2m_k_correspondences_;
+  double gicps2m_max_corr_dist_;
+  int gicps2m_max_iter_;
+  double gicps2m_transformation_ep_;
+  double gicps2m_euclidean_fitness_ep_;
+  int gicps2m_ransac_iter_;
+  double gicps2m_ransac_inlier_thresh_;
+
+};

+ 51 - 0
include/nano_gicp/gicp/gicp_settings.hpp

@@ -0,0 +1,51 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_GICP_NANO_SETTINGS_HPP
+#define NANO_GICP_NANO_SETTINGS_HPP
+
+namespace nano_gicp {
+
+  enum class RegularizationMethod { NONE, MIN_EIG, NORMALIZED_MIN_EIG, PLANE, FROBENIUS };
+
+}
+
+#endif

+ 122 - 0
include/nano_gicp/gicp/so3.hpp

@@ -0,0 +1,122 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_GICP_SO3_HPP
+#define NANO_GICP_SO3_HPP
+
+#include <Eigen/Core>
+#include <Eigen/Geometry>
+
+namespace nano_gicp {
+
+inline Eigen::Matrix3f skew(const Eigen::Vector3f& x) {
+  Eigen::Matrix3f skew = Eigen::Matrix3f::Zero();
+  skew(0, 1) = -x[2];
+  skew(0, 2) = x[1];
+  skew(1, 0) = x[2];
+  skew(1, 2) = -x[0];
+  skew(2, 0) = -x[1];
+  skew(2, 1) = x[0];
+
+  return skew;
+}
+
+inline Eigen::Matrix3d skewd(const Eigen::Vector3d& x) {
+  Eigen::Matrix3d skew = Eigen::Matrix3d::Zero();
+  skew(0, 1) = -x[2];
+  skew(0, 2) = x[1];
+  skew(1, 0) = x[2];
+  skew(1, 2) = -x[0];
+  skew(2, 0) = -x[1];
+  skew(2, 1) = x[0];
+
+  return skew;
+}
+
+/*
+ * SO3 expmap code taken from Sophus
+ * https://github.com/strasdat/Sophus/blob/593db47500ea1a2de5f0e6579c86147991509c59/sophus/so3.hpp#L585
+ *
+ * Copyright 2011-2017 Hauke Strasdat
+ *           2012-2017 Steven Lovegrove
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights  to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+inline Eigen::Quaterniond so3_exp(const Eigen::Vector3d& omega) {
+  double theta_sq = omega.dot(omega);
+
+  double theta;
+  double imag_factor;
+  double real_factor;
+  if(theta_sq < 1e-10) {
+    theta = 0;
+    double theta_quad = theta_sq * theta_sq;
+    imag_factor = 0.5 - 1.0 / 48.0 * theta_sq + 1.0 / 3840.0 * theta_quad;
+    real_factor = 1.0 - 1.0 / 8.0 * theta_sq + 1.0 / 384.0 * theta_quad;
+  } else {
+    theta = std::sqrt(theta_sq);
+    double half_theta = 0.5 * theta;
+    imag_factor = std::sin(half_theta) / theta;
+    real_factor = std::cos(half_theta);
+  }
+
+  return Eigen::Quaterniond(real_factor, imag_factor * omega.x(), imag_factor * omega.y(), imag_factor * omega.z());
+}
+
+}  // namespace nano_gicp
+
+#endif

+ 210 - 0
include/nano_gicp/impl/lsq_registration_impl.hpp

@@ -0,0 +1,210 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#include <boost/format.hpp>
+
+#include <nano_gicp/lsq_registration.hpp>
+#include <nano_gicp/gicp/so3.hpp>
+
+namespace nano_gicp {
+
+template <typename PointTarget, typename PointSource>
+LsqRegistration<PointTarget, PointSource>::LsqRegistration() {
+  this->reg_name_ = "LsqRegistration";
+  max_iterations_ = 64;
+  rotation_epsilon_ = 2e-3;
+  transformation_epsilon_ = 5e-4;
+
+  lsq_optimizer_type_ = LSQ_OPTIMIZER_TYPE::LevenbergMarquardt;
+  lm_debug_print_ = false;
+  lm_max_iterations_ = 10;
+  lm_init_lambda_factor_ = 1e-9;
+  lm_lambda_ = -1.0;
+
+  final_hessian_.setIdentity();
+}
+
+template <typename PointTarget, typename PointSource>
+LsqRegistration<PointTarget, PointSource>::~LsqRegistration() {}
+
+template <typename PointTarget, typename PointSource>
+void LsqRegistration<PointTarget, PointSource>::setRotationEpsilon(double eps) {
+  rotation_epsilon_ = eps;
+}
+
+template <typename PointTarget, typename PointSource>
+void LsqRegistration<PointTarget, PointSource>::setInitialLambdaFactor(double init_lambda_factor) {
+  lm_init_lambda_factor_ = init_lambda_factor;
+}
+
+template <typename PointTarget, typename PointSource>
+void LsqRegistration<PointTarget, PointSource>::setDebugPrint(bool lm_debug_print) {
+  lm_debug_print_ = lm_debug_print;
+}
+
+template <typename PointTarget, typename PointSource>
+const Eigen::Matrix<double, 6, 6>& LsqRegistration<PointTarget, PointSource>::getFinalHessian() const {
+  return final_hessian_;
+}
+
+template <typename PointTarget, typename PointSource>
+void LsqRegistration<PointTarget, PointSource>::computeTransformation(PointCloudSource& output, const Matrix4& guess) {
+  Eigen::Isometry3d x0 = Eigen::Isometry3d(guess.template cast<double>());
+
+  lm_lambda_ = -1.0;
+  converged_ = false;
+
+  if (lm_debug_print_) {
+    std::cout << "********************************************" << std::endl;
+    std::cout << "***************** optimize *****************" << std::endl;
+    std::cout << "********************************************" << std::endl;
+  }
+
+  for (int i = 0; i < max_iterations_ && !converged_; i++) {
+    nr_iterations_ = i;
+
+    Eigen::Isometry3d delta;
+    if (!step_optimize(x0, delta)) {
+      std::cerr << "lm not converged!!" << std::endl;
+      break;
+    }
+
+    converged_ = is_converged(delta);
+  }
+
+  final_transformation_ = x0.cast<float>().matrix();
+  pcl::transformPointCloud(*input_, output, final_transformation_);
+}
+
+template <typename PointTarget, typename PointSource>
+bool LsqRegistration<PointTarget, PointSource>::is_converged(const Eigen::Isometry3d& delta) const {
+  double accum = 0.0;
+  Eigen::Matrix3d R = delta.linear() - Eigen::Matrix3d::Identity();
+  Eigen::Vector3d t = delta.translation();
+
+  Eigen::Matrix3d r_delta = 1.0 / rotation_epsilon_ * R.array().abs();
+  Eigen::Vector3d t_delta = 1.0 / transformation_epsilon_ * t.array().abs();
+
+  return std::max(r_delta.maxCoeff(), t_delta.maxCoeff()) < 1;
+}
+
+template <typename PointTarget, typename PointSource>
+bool LsqRegistration<PointTarget, PointSource>::step_optimize(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta) {
+  switch (lsq_optimizer_type_) {
+    case LSQ_OPTIMIZER_TYPE::LevenbergMarquardt:
+      return step_lm(x0, delta);
+    case LSQ_OPTIMIZER_TYPE::GaussNewton:
+      return step_gn(x0, delta);
+  }
+
+  return step_lm(x0, delta);
+}
+
+template <typename PointTarget, typename PointSource>
+bool LsqRegistration<PointTarget, PointSource>::step_gn(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta) {
+  Eigen::Matrix<double, 6, 6> H;
+  Eigen::Matrix<double, 6, 1> b;
+  double y0 = linearize(x0, &H, &b);
+
+  Eigen::LDLT<Eigen::Matrix<double, 6, 6>> solver(H);
+  Eigen::Matrix<double, 6, 1> d = solver.solve(-b);
+
+  delta.setIdentity();
+  delta.linear() = so3_exp(d.head<3>()).toRotationMatrix();
+  delta.translation() = d.tail<3>();
+
+  x0 = delta * x0;
+  final_hessian_ = H;
+
+  return true;
+}
+
+template <typename PointTarget, typename PointSource>
+bool LsqRegistration<PointTarget, PointSource>::step_lm(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta) {
+  Eigen::Matrix<double, 6, 6> H;
+  Eigen::Matrix<double, 6, 1> b;
+  double y0 = linearize(x0, &H, &b);
+
+  if (lm_lambda_ < 0.0) {
+    lm_lambda_ = lm_init_lambda_factor_ * H.diagonal().array().abs().maxCoeff();
+  }
+
+  double nu = 2.0;
+  for (int i = 0; i < lm_max_iterations_; i++) {
+    Eigen::LDLT<Eigen::Matrix<double, 6, 6>> solver(H + lm_lambda_ * Eigen::Matrix<double, 6, 6>::Identity());
+    Eigen::Matrix<double, 6, 1> d = solver.solve(-b);
+
+    delta.setIdentity();
+    delta.linear() = so3_exp(d.head<3>()).toRotationMatrix();
+    delta.translation() = d.tail<3>();
+
+    Eigen::Isometry3d xi = delta * x0;
+    double yi = compute_error(xi);
+    double rho = (y0 - yi) / (d.dot(lm_lambda_ * d - b));
+
+    if (lm_debug_print_) {
+      if (i == 0) {
+        std::cout << boost::format("--- LM optimization ---\n%5s %15s %15s %15s %15s %15s %5s\n") % "i" % "y0" % "yi" % "rho" % "lambda" % "|delta|" % "dec";
+      }
+      char dec = rho > 0.0 ? 'x' : ' ';
+      std::cout << boost::format("%5d %15g %15g %15g %15g %15g %5c") % i % y0 % yi % rho % lm_lambda_ % d.norm() % dec << std::endl;
+    }
+
+    if (rho < 0) {
+      if (is_converged(delta)) {
+        return true;
+      }
+
+      lm_lambda_ = nu * lm_lambda_;
+      nu = 2 * nu;
+      continue;
+    }
+
+    x0 = xi;
+    lm_lambda_ = lm_lambda_ * std::max(1.0 / 3.0, 1 - std::pow(2 * rho - 1, 3));
+    final_hessian_ = H;
+    return true;
+  }
+
+  return false;
+}
+
+}  // namespace nano_gicp

+ 351 - 0
include/nano_gicp/impl/nano_gicp_impl.hpp

@@ -0,0 +1,351 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_GICP_NANO_GICP_IMPL_HPP
+#define NANO_GICP_NANO_GICP_IMPL_HPP
+
+#include <nano_gicp/gicp/so3.hpp>
+
+namespace nano_gicp {
+
+template <typename PointSource, typename PointTarget>
+NanoGICP<PointSource, PointTarget>::NanoGICP() {
+#ifdef _OPENMP
+  num_threads_ = omp_get_max_threads();
+#else
+  num_threads_ = 1;
+#endif
+
+  k_correspondences_ = 20;
+  reg_name_ = "NanoGICP";
+  corr_dist_threshold_ = std::numeric_limits<float>::max();
+
+  regularization_method_ = RegularizationMethod::PLANE;
+  source_kdtree_.reset(new nanoflann::KdTreeFLANN<PointSource>);
+  target_kdtree_.reset(new nanoflann::KdTreeFLANN<PointTarget>);
+}
+
+template <typename PointSource, typename PointTarget>
+NanoGICP<PointSource, PointTarget>::~NanoGICP() {}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setNumThreads(int n) {
+  num_threads_ = n;
+
+#ifdef _OPENMP
+  if (n == 0) {
+    num_threads_ = omp_get_max_threads();
+  }
+#endif
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setCorrespondenceRandomness(int k) {
+  k_correspondences_ = k;
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setRegularizationMethod(RegularizationMethod method) {
+  regularization_method_ = method;
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::swapSourceAndTarget() {
+  input_.swap(target_);
+  source_kdtree_.swap(target_kdtree_);
+  source_covs_.swap(target_covs_);
+
+  correspondences_.clear();
+  sq_distances_.clear();
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::clearSource() {
+  input_.reset();
+  source_covs_.clear();
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::clearTarget() {
+  target_.reset();
+  target_covs_.clear();
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::registerInputSource(const PointCloudSourceConstPtr& cloud) {
+  if (input_ == cloud) {
+    return;
+  }
+  pcl::Registration<PointSource, PointTarget, Scalar>::setInputSource(cloud);
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setInputSource(const PointCloudSourceConstPtr& cloud) {
+  if (input_ == cloud) {
+    return;
+  }
+
+  pcl::Registration<PointSource, PointTarget, Scalar>::setInputSource(cloud);
+  source_kdtree_->setInputCloud(cloud);
+  source_covs_.clear();
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setInputTarget(const PointCloudTargetConstPtr& cloud) {
+  if (target_ == cloud) {
+    return;
+  }
+  pcl::Registration<PointSource, PointTarget, Scalar>::setInputTarget(cloud);
+  target_kdtree_->setInputCloud(cloud);
+  target_covs_.clear();
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setSourceCovariances(const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covs) {
+  source_covs_ = covs;
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::setTargetCovariances(const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covs) {
+  target_covs_ = covs;
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::computeTransformation(PointCloudSource& output, const Matrix4& guess) {
+  if (source_covs_.size() != input_->size()) {
+    calculate_covariances(input_, *source_kdtree_, source_covs_);
+  }
+  if (target_covs_.size() != target_->size()) {
+    calculate_covariances(target_, *target_kdtree_, target_covs_);
+  }
+
+  LsqRegistration<PointSource, PointTarget>::computeTransformation(output, guess);
+}
+
+template <typename PointSource, typename PointTarget>
+void NanoGICP<PointSource, PointTarget>::update_correspondences(const Eigen::Isometry3d& trans) {
+  assert(source_covs_.size() == input_->size());
+  assert(target_covs_.size() == target_->size());
+
+  Eigen::Isometry3f trans_f = trans.cast<float>();
+
+  correspondences_.resize(input_->size());
+  sq_distances_.resize(input_->size());
+  mahalanobis_.resize(input_->size());
+
+  std::vector<int> k_indices(1);
+  std::vector<float> k_sq_dists(1);
+
+#pragma omp parallel for num_threads(num_threads_) firstprivate(k_indices, k_sq_dists) schedule(guided, 8)
+  for (int i = 0; i < input_->size(); i++) {
+    PointTarget pt;
+    pt.getVector4fMap() = trans_f * input_->at(i).getVector4fMap();
+
+    target_kdtree_->nearestKSearch(pt, 1, k_indices, k_sq_dists);
+
+    sq_distances_[i] = k_sq_dists[0];
+    correspondences_[i] = k_sq_dists[0] < corr_dist_threshold_ * corr_dist_threshold_ ? k_indices[0] : -1;
+
+    if (correspondences_[i] < 0) {
+      continue;
+    }
+
+    const int target_index = correspondences_[i];
+    const auto& cov_A = source_covs_[i];
+    const auto& cov_B = target_covs_[target_index];
+
+    Eigen::Matrix4d RCR = cov_B + trans.matrix() * cov_A * trans.matrix().transpose();
+    RCR(3, 3) = 1.0;
+
+    mahalanobis_[i] = RCR.inverse();
+    mahalanobis_[i](3, 3) = 0.0f;
+  }
+}
+
+template <typename PointSource, typename PointTarget>
+double NanoGICP<PointSource, PointTarget>::linearize(const Eigen::Isometry3d& trans, Eigen::Matrix<double, 6, 6>* H, Eigen::Matrix<double, 6, 1>* b) {
+  update_correspondences(trans);
+
+  double sum_errors = 0.0;
+  std::vector<Eigen::Matrix<double, 6, 6>, Eigen::aligned_allocator<Eigen::Matrix<double, 6, 6>>> Hs(num_threads_);
+  std::vector<Eigen::Matrix<double, 6, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, 6, 1>>> bs(num_threads_);
+  for (int i = 0; i < num_threads_; i++) {
+    Hs[i].setZero();
+    bs[i].setZero();
+  }
+
+#pragma omp parallel for num_threads(num_threads_) reduction(+ : sum_errors) schedule(guided, 8)
+  for (int i = 0; i < input_->size(); i++) {
+    int target_index = correspondences_[i];
+    if (target_index < 0) {
+      continue;
+    }
+
+    const Eigen::Vector4d mean_A = input_->at(i).getVector4fMap().template cast<double>();
+    const auto& cov_A = source_covs_[i];
+
+    const Eigen::Vector4d mean_B = target_->at(target_index).getVector4fMap().template cast<double>();
+    const auto& cov_B = target_covs_[target_index];
+
+    const Eigen::Vector4d transed_mean_A = trans * mean_A;
+    const Eigen::Vector4d error = mean_B - transed_mean_A;
+
+    sum_errors += error.transpose() * mahalanobis_[i] * error;
+
+    if (H == nullptr || b == nullptr) {
+      continue;
+    }
+
+    Eigen::Matrix<double, 4, 6> dtdx0 = Eigen::Matrix<double, 4, 6>::Zero();
+    dtdx0.block<3, 3>(0, 0) = skewd(transed_mean_A.head<3>());
+    dtdx0.block<3, 3>(0, 3) = -Eigen::Matrix3d::Identity();
+
+    Eigen::Matrix<double, 4, 6> jlossexp = dtdx0;
+
+    Eigen::Matrix<double, 6, 6> Hi = jlossexp.transpose() * mahalanobis_[i] * jlossexp;
+    Eigen::Matrix<double, 6, 1> bi = jlossexp.transpose() * mahalanobis_[i] * error;
+
+    Hs[omp_get_thread_num()] += Hi;
+    bs[omp_get_thread_num()] += bi;
+  }
+
+  if (H && b) {
+    H->setZero();
+    b->setZero();
+    for (int i = 0; i < num_threads_; i++) {
+      (*H) += Hs[i];
+      (*b) += bs[i];
+    }
+  }
+
+  return sum_errors;
+}
+
+template <typename PointSource, typename PointTarget>
+double NanoGICP<PointSource, PointTarget>::compute_error(const Eigen::Isometry3d& trans) {
+  double sum_errors = 0.0;
+
+#pragma omp parallel for num_threads(num_threads_) reduction(+ : sum_errors) schedule(guided, 8)
+  for (int i = 0; i < input_->size(); i++) {
+    int target_index = correspondences_[i];
+    if (target_index < 0) {
+      continue;
+    }
+
+    const Eigen::Vector4d mean_A = input_->at(i).getVector4fMap().template cast<double>();
+    const auto& cov_A = source_covs_[i];
+
+    const Eigen::Vector4d mean_B = target_->at(target_index).getVector4fMap().template cast<double>();
+    const auto& cov_B = target_covs_[target_index];
+
+    const Eigen::Vector4d transed_mean_A = trans * mean_A;
+    const Eigen::Vector4d error = mean_B - transed_mean_A;
+
+    sum_errors += error.transpose() * mahalanobis_[i] * error;
+  }
+
+  return sum_errors;
+}
+
+template <typename PointSource, typename PointTarget>
+template <typename PointT>
+bool NanoGICP<PointSource, PointTarget>::calculate_covariances(
+  const typename pcl::PointCloud<PointT>::ConstPtr& cloud,
+  nanoflann::KdTreeFLANN<PointT>& kdtree,
+  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covariances) {
+  if (kdtree.getInputCloud() != cloud) {
+    kdtree.setInputCloud(cloud);
+  }
+  covariances.resize(cloud->size());
+
+#pragma omp parallel for num_threads(num_threads_) schedule(guided, 8)
+  for (int i = 0; i < cloud->size(); i++) {
+    std::vector<int> k_indices;
+    std::vector<float> k_sq_distances;
+    kdtree.nearestKSearch(cloud->at(i), k_correspondences_, k_indices, k_sq_distances);
+
+    Eigen::Matrix<double, 4, -1> neighbors(4, k_correspondences_);
+    for (int j = 0; j < k_indices.size(); j++) {
+      neighbors.col(j) = cloud->at(k_indices[j]).getVector4fMap().template cast<double>();
+    }
+
+    neighbors.colwise() -= neighbors.rowwise().mean().eval();
+    Eigen::Matrix4d cov = neighbors * neighbors.transpose() / k_correspondences_;
+
+    if (regularization_method_ == RegularizationMethod::NONE) {
+      covariances[i] = cov;
+    } else if (regularization_method_ == RegularizationMethod::FROBENIUS) {
+      double lambda = 1e-3;
+      Eigen::Matrix3d C = cov.block<3, 3>(0, 0).cast<double>() + lambda * Eigen::Matrix3d::Identity();
+      Eigen::Matrix3d C_inv = C.inverse();
+      covariances[i].setZero();
+      covariances[i].template block<3, 3>(0, 0) = (C_inv / C_inv.norm()).inverse();
+    } else {
+      Eigen::JacobiSVD<Eigen::Matrix3d> svd(cov.block<3, 3>(0, 0), Eigen::ComputeFullU | Eigen::ComputeFullV);
+      Eigen::Vector3d values;
+
+      switch (regularization_method_) {
+        default:
+          std::cerr << "here must not be reached" << std::endl;
+          abort();
+        case RegularizationMethod::PLANE:
+          values = Eigen::Vector3d(1, 1, 1e-3);
+          break;
+        case RegularizationMethod::MIN_EIG:
+          values = svd.singularValues().array().max(1e-3);
+          break;
+        case RegularizationMethod::NORMALIZED_MIN_EIG:
+          values = svd.singularValues() / svd.singularValues().maxCoeff();
+          values = values.array().max(1e-3);
+          break;
+      }
+
+      covariances[i].setZero();
+      covariances[i].template block<3, 3>(0, 0) = svd.matrixU() * values.asDiagonal() * svd.matrixV().transpose();
+    }
+  }
+
+  return true;
+}
+
+}  // namespace nano_gicp
+
+#endif

+ 2057 - 0
include/nano_gicp/impl/nanoflann_impl.hpp

@@ -0,0 +1,2057 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ * Copyright 2011-2021  Jose Luis Blanco (joseluisblancoc@gmail.com).
+ *   All rights reserved.
+ *
+ * THE BSD LICENSE
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+/** \mainpage nanoflann C++ API documentation
+ *  nanoflann is a C++ header-only library for building KD-Trees, mostly
+ *  optimized for 2D or 3D point clouds.
+ *
+ *  nanoflann does not require compiling or installing, just an
+ *  #include <nanoflann.hpp> in your code.
+ *
+ *  See:
+ *   - <a href="modules.html" >C++ API organized by modules</a>
+ *   - <a href="https://github.com/jlblancoc/nanoflann" >Online README</a>
+ *   - <a href="http://jlblancoc.github.io/nanoflann/" >Doxygen
+ * documentation</a>
+ */
+
+#ifndef NANOFLANN_HPP_
+#define NANOFLANN_HPP_
+
+#include <algorithm>
+#include <array>
+#include <cassert>
+#include <cmath>   // for abs()
+#include <cstdio>  // for fwrite()
+#include <cstdlib> // for abs()
+#include <functional>
+#include <limits> // std::reference_wrapper
+#include <stdexcept>
+#include <vector>
+
+/** Library version: 0xMmP (M=Major,m=minor,P=patch) */
+#define NANOFLANN_VERSION 0x132
+
+// Avoid conflicting declaration of min/max macros in windows headers
+#if !defined(NOMINMAX) &&                                                      \
+    (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64))
+#define NOMINMAX
+#ifdef max
+#undef max
+#undef min
+#endif
+#endif
+
+namespace nanoflann {
+/** @addtogroup nanoflann_grp nanoflann C++ library for ANN
+ *  @{ */
+
+/** the PI constant (required to avoid MSVC missing symbols) */
+template <typename T> T pi_const() {
+  return static_cast<T>(3.14159265358979323846);
+}
+
+/**
+ * Traits if object is resizable and assignable (typically has a resize | assign
+ * method)
+ */
+template <typename T, typename = int> struct has_resize : std::false_type {};
+
+template <typename T>
+struct has_resize<T, decltype((void)std::declval<T>().resize(1), 0)>
+    : std::true_type {};
+
+template <typename T, typename = int> struct has_assign : std::false_type {};
+
+template <typename T>
+struct has_assign<T, decltype((void)std::declval<T>().assign(1, 0), 0)>
+    : std::true_type {};
+
+/**
+ * Free function to resize a resizable object
+ */
+template <typename Container>
+inline typename std::enable_if<has_resize<Container>::value, void>::type
+resize(Container &c, const size_t nElements) {
+  c.resize(nElements);
+}
+
+/**
+ * Free function that has no effects on non resizable containers (e.g.
+ * std::array) It raises an exception if the expected size does not match
+ */
+template <typename Container>
+inline typename std::enable_if<!has_resize<Container>::value, void>::type
+resize(Container &c, const size_t nElements) {
+  if (nElements != c.size())
+    throw std::logic_error("Try to change the size of a std::array.");
+}
+
+/**
+ * Free function to assign to a container
+ */
+template <typename Container, typename T>
+inline typename std::enable_if<has_assign<Container>::value, void>::type
+assign(Container &c, const size_t nElements, const T &value) {
+  c.assign(nElements, value);
+}
+
+/**
+ * Free function to assign to a std::array
+ */
+template <typename Container, typename T>
+inline typename std::enable_if<!has_assign<Container>::value, void>::type
+assign(Container &c, const size_t nElements, const T &value) {
+  for (size_t i = 0; i < nElements; i++)
+    c[i] = value;
+}
+
+/** @addtogroup result_sets_grp Result set classes
+ *  @{ */
+template <typename _DistanceType, typename _IndexType = size_t,
+          typename _CountType = size_t>
+class KNNResultSet {
+public:
+  typedef _DistanceType DistanceType;
+  typedef _IndexType IndexType;
+  typedef _CountType CountType;
+
+private:
+  IndexType *indices;
+  DistanceType *dists;
+  CountType capacity;
+  CountType count;
+
+public:
+  inline KNNResultSet(CountType capacity_)
+      : indices(0), dists(0), capacity(capacity_), count(0) {}
+
+  inline void init(IndexType *indices_, DistanceType *dists_) {
+    indices = indices_;
+    dists = dists_;
+    count = 0;
+    if (capacity)
+      dists[capacity - 1] = (std::numeric_limits<DistanceType>::max)();
+  }
+
+  inline CountType size() const { return count; }
+
+  inline bool full() const { return count == capacity; }
+
+  /**
+   * Called during search to add an element matching the criteria.
+   * @return true if the search should be continued, false if the results are
+   * sufficient
+   */
+  inline bool addPoint(DistanceType dist, IndexType index) {
+    CountType i;
+    for (i = count; i > 0; --i) {
+#ifdef NANOFLANN_FIRST_MATCH // If defined and two points have the same
+                             // distance, the one with the lowest-index will be
+                             // returned first.
+      if ((dists[i - 1] > dist) ||
+          ((dist == dists[i - 1]) && (indices[i - 1] > index))) {
+#else
+      if (dists[i - 1] > dist) {
+#endif
+        if (i < capacity) {
+          dists[i] = dists[i - 1];
+          indices[i] = indices[i - 1];
+        }
+      } else
+        break;
+    }
+    if (i < capacity) {
+      dists[i] = dist;
+      indices[i] = index;
+    }
+    if (count < capacity)
+      count++;
+
+    // tell caller that the search shall continue
+    return true;
+  }
+
+  inline DistanceType worstDist() const { return dists[capacity - 1]; }
+};
+
+/** operator "<" for std::sort() */
+struct IndexDist_Sorter {
+  /** PairType will be typically: std::pair<IndexType,DistanceType> */
+  template <typename PairType>
+  inline bool operator()(const PairType &p1, const PairType &p2) const {
+    return p1.second < p2.second;
+  }
+};
+
+/**
+ * A result-set class used when performing a radius based search.
+ */
+template <typename _DistanceType, typename _IndexType = size_t>
+class RadiusResultSet {
+public:
+  typedef _DistanceType DistanceType;
+  typedef _IndexType IndexType;
+
+public:
+  const DistanceType radius;
+
+  std::vector<std::pair<IndexType, DistanceType>> &m_indices_dists;
+
+  inline RadiusResultSet(
+      DistanceType radius_,
+      std::vector<std::pair<IndexType, DistanceType>> &indices_dists)
+      : radius(radius_), m_indices_dists(indices_dists) {
+    init();
+  }
+
+  inline void init() { clear(); }
+  inline void clear() { m_indices_dists.clear(); }
+
+  inline size_t size() const { return m_indices_dists.size(); }
+
+  inline bool full() const { return true; }
+
+  /**
+   * Called during search to add an element matching the criteria.
+   * @return true if the search should be continued, false if the results are
+   * sufficient
+   */
+  inline bool addPoint(DistanceType dist, IndexType index) {
+    if (dist < radius)
+      m_indices_dists.push_back(std::make_pair(index, dist));
+    return true;
+  }
+
+  inline DistanceType worstDist() const { return radius; }
+
+  /**
+   * Find the worst result (furtherest neighbor) without copying or sorting
+   * Pre-conditions: size() > 0
+   */
+  std::pair<IndexType, DistanceType> worst_item() const {
+    if (m_indices_dists.empty())
+      throw std::runtime_error("Cannot invoke RadiusResultSet::worst_item() on "
+                               "an empty list of results.");
+    typedef
+        typename std::vector<std::pair<IndexType, DistanceType>>::const_iterator
+            DistIt;
+    DistIt it = std::max_element(m_indices_dists.begin(), m_indices_dists.end(),
+                                 IndexDist_Sorter());
+    return *it;
+  }
+};
+
+/** @} */
+
+/** @addtogroup loadsave_grp Load/save auxiliary functions
+ * @{ */
+template <typename T>
+void save_value(FILE *stream, const T &value, size_t count = 1) {
+  fwrite(&value, sizeof(value), count, stream);
+}
+
+template <typename T>
+void save_value(FILE *stream, const std::vector<T> &value) {
+  size_t size = value.size();
+  fwrite(&size, sizeof(size_t), 1, stream);
+  fwrite(&value[0], sizeof(T), size, stream);
+}
+
+template <typename T>
+void load_value(FILE *stream, T &value, size_t count = 1) {
+  size_t read_cnt = fread(&value, sizeof(value), count, stream);
+  if (read_cnt != count) {
+    throw std::runtime_error("Cannot read from file");
+  }
+}
+
+template <typename T> void load_value(FILE *stream, std::vector<T> &value) {
+  size_t size;
+  size_t read_cnt = fread(&size, sizeof(size_t), 1, stream);
+  if (read_cnt != 1) {
+    throw std::runtime_error("Cannot read from file");
+  }
+  value.resize(size);
+  read_cnt = fread(&value[0], sizeof(T), size, stream);
+  if (read_cnt != size) {
+    throw std::runtime_error("Cannot read from file");
+  }
+}
+/** @} */
+
+/** @addtogroup metric_grp Metric (distance) classes
+ * @{ */
+
+struct Metric {};
+
+/** Manhattan distance functor (generic version, optimized for
+ * high-dimensionality data sets). Corresponding distance traits:
+ * nanoflann::metric_L1 \tparam T Type of the elements (e.g. double, float,
+ * uint8_t) \tparam _DistanceType Type of distance variables (must be signed)
+ * (e.g. float, double, int64_t)
+ */
+template <class T, class DataSource, typename _DistanceType = T>
+struct L1_Adaptor {
+  typedef T ElementType;
+  typedef _DistanceType DistanceType;
+
+  const DataSource &data_source;
+
+  L1_Adaptor(const DataSource &_data_source) : data_source(_data_source) {}
+
+  inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size,
+                                 DistanceType worst_dist = -1) const {
+    DistanceType result = DistanceType();
+    const T *last = a + size;
+    const T *lastgroup = last - 3;
+    size_t d = 0;
+
+    /* Process 4 items with each loop for efficiency. */
+    while (a < lastgroup) {
+      const DistanceType diff0 =
+          std::abs(a[0] - data_source.kdtree_get_pt(b_idx, d++));
+      const DistanceType diff1 =
+          std::abs(a[1] - data_source.kdtree_get_pt(b_idx, d++));
+      const DistanceType diff2 =
+          std::abs(a[2] - data_source.kdtree_get_pt(b_idx, d++));
+      const DistanceType diff3 =
+          std::abs(a[3] - data_source.kdtree_get_pt(b_idx, d++));
+      result += diff0 + diff1 + diff2 + diff3;
+      a += 4;
+      if ((worst_dist > 0) && (result > worst_dist)) {
+        return result;
+      }
+    }
+    /* Process last 0-3 components.  Not needed for standard vector lengths. */
+    while (a < last) {
+      result += std::abs(*a++ - data_source.kdtree_get_pt(b_idx, d++));
+    }
+    return result;
+  }
+
+  template <typename U, typename V>
+  inline DistanceType accum_dist(const U a, const V b, const size_t) const {
+    return std::abs(a - b);
+  }
+};
+
+/** Squared Euclidean distance functor (generic version, optimized for
+ * high-dimensionality data sets). Corresponding distance traits:
+ * nanoflann::metric_L2 \tparam T Type of the elements (e.g. double, float,
+ * uint8_t) \tparam _DistanceType Type of distance variables (must be signed)
+ * (e.g. float, double, int64_t)
+ */
+template <class T, class DataSource, typename _DistanceType = T>
+struct L2_Adaptor {
+  typedef T ElementType;
+  typedef _DistanceType DistanceType;
+
+  const DataSource &data_source;
+
+  L2_Adaptor(const DataSource &_data_source) : data_source(_data_source) {}
+
+  inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size,
+                                 DistanceType worst_dist = -1) const {
+    DistanceType result = DistanceType();
+    const T *last = a + size;
+    const T *lastgroup = last - 3;
+    size_t d = 0;
+
+    /* Process 4 items with each loop for efficiency. */
+    while (a < lastgroup) {
+      const DistanceType diff0 = a[0] - data_source.kdtree_get_pt(b_idx, d++);
+      const DistanceType diff1 = a[1] - data_source.kdtree_get_pt(b_idx, d++);
+      const DistanceType diff2 = a[2] - data_source.kdtree_get_pt(b_idx, d++);
+      const DistanceType diff3 = a[3] - data_source.kdtree_get_pt(b_idx, d++);
+      result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
+      a += 4;
+      if ((worst_dist > 0) && (result > worst_dist)) {
+        return result;
+      }
+    }
+    /* Process last 0-3 components.  Not needed for standard vector lengths. */
+    while (a < last) {
+      const DistanceType diff0 = *a++ - data_source.kdtree_get_pt(b_idx, d++);
+      result += diff0 * diff0;
+    }
+    return result;
+  }
+
+  template <typename U, typename V>
+  inline DistanceType accum_dist(const U a, const V b, const size_t) const {
+    return (a - b) * (a - b);
+  }
+};
+
+/** Squared Euclidean (L2) distance functor (suitable for low-dimensionality
+ * datasets, like 2D or 3D point clouds) Corresponding distance traits:
+ * nanoflann::metric_L2_Simple \tparam T Type of the elements (e.g. double,
+ * float, uint8_t) \tparam _DistanceType Type of distance variables (must be
+ * signed) (e.g. float, double, int64_t)
+ */
+template <class T, class DataSource, typename _DistanceType = T>
+struct L2_Simple_Adaptor {
+  typedef T ElementType;
+  typedef _DistanceType DistanceType;
+
+  const DataSource &data_source;
+
+  L2_Simple_Adaptor(const DataSource &_data_source)
+      : data_source(_data_source) {}
+
+  inline DistanceType evalMetric(const T *a, const size_t b_idx,
+                                 size_t size) const {
+    DistanceType result = DistanceType();
+    for (size_t i = 0; i < size; ++i) {
+      const DistanceType diff = a[i] - data_source.kdtree_get_pt(b_idx, i);
+      result += diff * diff;
+    }
+    return result;
+  }
+
+  template <typename U, typename V>
+  inline DistanceType accum_dist(const U a, const V b, const size_t) const {
+    return (a - b) * (a - b);
+  }
+};
+
+/** SO2 distance functor
+ *  Corresponding distance traits: nanoflann::metric_SO2
+ * \tparam T Type of the elements (e.g. double, float)
+ * \tparam _DistanceType Type of distance variables (must be signed) (e.g.
+ * float, double) orientation is constrained to be in [-pi, pi]
+ */
+template <class T, class DataSource, typename _DistanceType = T>
+struct SO2_Adaptor {
+  typedef T ElementType;
+  typedef _DistanceType DistanceType;
+
+  const DataSource &data_source;
+
+  SO2_Adaptor(const DataSource &_data_source) : data_source(_data_source) {}
+
+  inline DistanceType evalMetric(const T *a, const size_t b_idx,
+                                 size_t size) const {
+    return accum_dist(a[size - 1], data_source.kdtree_get_pt(b_idx, size - 1),
+                      size - 1);
+  }
+
+  /** Note: this assumes that input angles are already in the range [-pi,pi] */
+  template <typename U, typename V>
+  inline DistanceType accum_dist(const U a, const V b, const size_t) const {
+    DistanceType result = DistanceType();
+    DistanceType PI = pi_const<DistanceType>();
+    result = b - a;
+    if (result > PI)
+      result -= 2 * PI;
+    else if (result < -PI)
+      result += 2 * PI;
+    return result;
+  }
+};
+
+/** SO3 distance functor (Uses L2_Simple)
+ *  Corresponding distance traits: nanoflann::metric_SO3
+ * \tparam T Type of the elements (e.g. double, float)
+ * \tparam _DistanceType Type of distance variables (must be signed) (e.g.
+ * float, double)
+ */
+template <class T, class DataSource, typename _DistanceType = T>
+struct SO3_Adaptor {
+  typedef T ElementType;
+  typedef _DistanceType DistanceType;
+
+  L2_Simple_Adaptor<T, DataSource> distance_L2_Simple;
+
+  SO3_Adaptor(const DataSource &_data_source)
+      : distance_L2_Simple(_data_source) {}
+
+  inline DistanceType evalMetric(const T *a, const size_t b_idx,
+                                 size_t size) const {
+    return distance_L2_Simple.evalMetric(a, b_idx, size);
+  }
+
+  template <typename U, typename V>
+  inline DistanceType accum_dist(const U a, const V b, const size_t idx) const {
+    return distance_L2_Simple.accum_dist(a, b, idx);
+  }
+};
+
+/** Metaprogramming helper traits class for the L1 (Manhattan) metric */
+struct metric_L1 : public Metric {
+  template <class T, class DataSource> struct traits {
+    typedef L1_Adaptor<T, DataSource> distance_t;
+  };
+};
+/** Metaprogramming helper traits class for the L2 (Euclidean) metric */
+struct metric_L2 : public Metric {
+  template <class T, class DataSource> struct traits {
+    typedef L2_Adaptor<T, DataSource> distance_t;
+  };
+};
+/** Metaprogramming helper traits class for the L2_simple (Euclidean) metric */
+struct metric_L2_Simple : public Metric {
+  template <class T, class DataSource> struct traits {
+    typedef L2_Simple_Adaptor<T, DataSource> distance_t;
+  };
+};
+/** Metaprogramming helper traits class for the SO3_InnerProdQuat metric */
+struct metric_SO2 : public Metric {
+  template <class T, class DataSource> struct traits {
+    typedef SO2_Adaptor<T, DataSource> distance_t;
+  };
+};
+/** Metaprogramming helper traits class for the SO3_InnerProdQuat metric */
+struct metric_SO3 : public Metric {
+  template <class T, class DataSource> struct traits {
+    typedef SO3_Adaptor<T, DataSource> distance_t;
+  };
+};
+
+/** @} */
+
+/** @addtogroup param_grp Parameter structs
+ * @{ */
+
+/**  Parameters (see README.md) */
+struct KDTreeSingleIndexAdaptorParams {
+  KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10)
+      : leaf_max_size(_leaf_max_size) {}
+
+  size_t leaf_max_size;
+};
+
+/** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */
+struct SearchParams {
+  /** Note: The first argument (checks_IGNORED_) is ignored, but kept for
+   * compatibility with the FLANN interface */
+  SearchParams(int checks_IGNORED_ = 32, float eps_ = 0, bool sorted_ = true)
+      : checks(checks_IGNORED_), eps(eps_), sorted(sorted_) {}
+
+  int checks;  //!< Ignored parameter (Kept for compatibility with the FLANN
+               //!< interface).
+  float eps;   //!< search for eps-approximate neighbours (default: 0)
+  bool sorted; //!< only for radius search, require neighbours sorted by
+               //!< distance (default: true)
+};
+/** @} */
+
+/** @addtogroup memalloc_grp Memory allocation
+ * @{ */
+
+/**
+ * Allocates (using C's malloc) a generic type T.
+ *
+ * Params:
+ *     count = number of instances to allocate.
+ * Returns: pointer (of type T*) to memory buffer
+ */
+template <typename T> inline T *allocate(size_t count = 1) {
+  T *mem = static_cast<T *>(::malloc(sizeof(T) * count));
+  return mem;
+}
+
+/**
+ * Pooled storage allocator
+ *
+ * The following routines allow for the efficient allocation of storage in
+ * small chunks from a specified pool.  Rather than allowing each structure
+ * to be freed individually, an entire pool of storage is freed at once.
+ * This method has two advantages over just using malloc() and free().  First,
+ * it is far more efficient for allocating small objects, as there is
+ * no overhead for remembering all the information needed to free each
+ * object or consolidating fragmented memory.  Second, the decision about
+ * how long to keep an object is made at the time of allocation, and there
+ * is no need to track down all the objects to free them.
+ *
+ */
+
+const size_t WORDSIZE = 16;
+const size_t BLOCKSIZE = 8192;
+
+class PooledAllocator {
+  /* We maintain memory alignment to word boundaries by requiring that all
+      allocations be in multiples of the machine wordsize.  */
+  /* Size of machine word in bytes.  Must be power of 2. */
+  /* Minimum number of bytes requested at a time from	the system.  Must be
+   * multiple of WORDSIZE. */
+
+  size_t remaining; /* Number of bytes left in current block of storage. */
+  void *base;       /* Pointer to base of current block of storage. */
+  void *loc;        /* Current location in block to next allocate memory. */
+
+  void internal_init() {
+    remaining = 0;
+    base = NULL;
+    usedMemory = 0;
+    wastedMemory = 0;
+  }
+
+public:
+  size_t usedMemory;
+  size_t wastedMemory;
+
+  /**
+      Default constructor. Initializes a new pool.
+   */
+  PooledAllocator() { internal_init(); }
+
+  /**
+   * Destructor. Frees all the memory allocated in this pool.
+   */
+  ~PooledAllocator() { free_all(); }
+
+  /** Frees all allocated memory chunks */
+  void free_all() {
+    while (base != NULL) {
+      void *prev =
+          *(static_cast<void **>(base)); /* Get pointer to prev block. */
+      ::free(base);
+      base = prev;
+    }
+    internal_init();
+  }
+
+  /**
+   * Returns a pointer to a piece of new memory of the given size in bytes
+   * allocated from the pool.
+   */
+  void *malloc(const size_t req_size) {
+    /* Round size up to a multiple of wordsize.  The following expression
+        only works for WORDSIZE that is a power of 2, by masking last bits of
+        incremented size to zero.
+     */
+    const size_t size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1);
+
+    /* Check whether a new block must be allocated.  Note that the first word
+        of a block is reserved for a pointer to the previous block.
+     */
+    if (size > remaining) {
+
+      wastedMemory += remaining;
+
+      /* Allocate new storage. */
+      const size_t blocksize =
+          (size + sizeof(void *) + (WORDSIZE - 1) > BLOCKSIZE)
+              ? size + sizeof(void *) + (WORDSIZE - 1)
+              : BLOCKSIZE;
+
+      // use the standard C malloc to allocate memory
+      void *m = ::malloc(blocksize);
+      if (!m) {
+        fprintf(stderr, "Failed to allocate memory.\n");
+        throw std::bad_alloc();
+      }
+
+      /* Fill first word of new block with pointer to previous block. */
+      static_cast<void **>(m)[0] = base;
+      base = m;
+
+      size_t shift = 0;
+      // int size_t = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) &
+      // (WORDSIZE-1))) & (WORDSIZE-1);
+
+      remaining = blocksize - sizeof(void *) - shift;
+      loc = (static_cast<char *>(m) + sizeof(void *) + shift);
+    }
+    void *rloc = loc;
+    loc = static_cast<char *>(loc) + size;
+    remaining -= size;
+
+    usedMemory += size;
+
+    return rloc;
+  }
+
+  /**
+   * Allocates (using this pool) a generic type T.
+   *
+   * Params:
+   *     count = number of instances to allocate.
+   * Returns: pointer (of type T*) to memory buffer
+   */
+  template <typename T> T *allocate(const size_t count = 1) {
+    T *mem = static_cast<T *>(this->malloc(sizeof(T) * count));
+    return mem;
+  }
+};
+/** @} */
+
+/** @addtogroup nanoflann_metaprog_grp Auxiliary metaprogramming stuff
+ * @{ */
+
+/** Used to declare fixed-size arrays when DIM>0, dynamically-allocated vectors
+ * when DIM=-1. Fixed size version for a generic DIM:
+ */
+template <int DIM, typename T> struct array_or_vector_selector {
+  typedef std::array<T, DIM> container_t;
+};
+/** Dynamic size version */
+template <typename T> struct array_or_vector_selector<-1, T> {
+  typedef std::vector<T> container_t;
+};
+
+/** @} */
+
+/** kd-tree base-class
+ *
+ * Contains the member functions common to the classes KDTreeSingleIndexAdaptor
+ * and KDTreeSingleIndexDynamicAdaptor_.
+ *
+ * \tparam Derived The name of the class which inherits this class.
+ * \tparam DatasetAdaptor The user-provided adaptor (see comments above).
+ * \tparam Distance The distance metric to use, these are all classes derived
+ * from nanoflann::Metric \tparam DIM Dimensionality of data points (e.g. 3 for
+ * 3D points) \tparam IndexType Will be typically size_t or int
+ */
+
+template <class Derived, typename Distance, class DatasetAdaptor, int DIM = -1,
+          typename IndexType = size_t>
+class KDTreeBaseClass {
+
+public:
+  /** Frees the previously-built index. Automatically called within
+   * buildIndex(). */
+  void freeIndex(Derived &obj) {
+    obj.pool.free_all();
+    obj.root_node = NULL;
+    obj.m_size_at_index_build = 0;
+  }
+
+  typedef typename Distance::ElementType ElementType;
+  typedef typename Distance::DistanceType DistanceType;
+
+  /*--------------------- Internal Data Structures --------------------------*/
+  struct Node {
+    /** Union used because a node can be either a LEAF node or a non-leaf node,
+     * so both data fields are never used simultaneously */
+    union {
+      struct leaf {
+        IndexType left, right; //!< Indices of points in leaf node
+      } lr;
+      struct nonleaf {
+        int divfeat;                  //!< Dimension used for subdivision.
+        DistanceType divlow, divhigh; //!< The values used for subdivision.
+      } sub;
+    } node_type;
+    Node *child1, *child2; //!< Child nodes (both=NULL mean its a leaf node)
+  };
+
+  typedef Node *NodePtr;
+
+  struct Interval {
+    ElementType low, high;
+  };
+
+  /**
+   *  Array of indices to vectors in the dataset.
+   */
+  std::vector<IndexType> vind;
+
+  NodePtr root_node;
+
+  size_t m_leaf_max_size;
+
+  size_t m_size;                //!< Number of current points in the dataset
+  size_t m_size_at_index_build; //!< Number of points in the dataset when the
+                                //!< index was built
+  int dim;                      //!< Dimensionality of each data point
+
+  /** Define "BoundingBox" as a fixed-size or variable-size container depending
+   * on "DIM" */
+  typedef
+      typename array_or_vector_selector<DIM, Interval>::container_t BoundingBox;
+
+  /** Define "distance_vector_t" as a fixed-size or variable-size container
+   * depending on "DIM" */
+  typedef typename array_or_vector_selector<DIM, DistanceType>::container_t
+      distance_vector_t;
+
+  /** The KD-tree used to find neighbours */
+
+  BoundingBox root_bbox;
+
+  /**
+   * Pooled memory allocator.
+   *
+   * Using a pooled memory allocator is more efficient
+   * than allocating memory directly when there is a large
+   * number small of memory allocations.
+   */
+  PooledAllocator pool;
+
+  /** Returns number of points in dataset  */
+  size_t size(const Derived &obj) const { return obj.m_size; }
+
+  /** Returns the length of each point in the dataset */
+  size_t veclen(const Derived &obj) {
+    return static_cast<size_t>(DIM > 0 ? DIM : obj.dim);
+  }
+
+  /// Helper accessor to the dataset points:
+  inline ElementType dataset_get(const Derived &obj, size_t idx,
+                                 int component) const {
+    return obj.dataset.kdtree_get_pt(idx, component);
+  }
+
+  /**
+   * Computes the inde memory usage
+   * Returns: memory used by the index
+   */
+  size_t usedMemory(Derived &obj) {
+    return obj.pool.usedMemory + obj.pool.wastedMemory +
+           obj.dataset.kdtree_get_point_count() *
+               sizeof(IndexType); // pool memory and vind array memory
+  }
+
+  void computeMinMax(const Derived &obj, IndexType *ind, IndexType count,
+                     int element, ElementType &min_elem,
+                     ElementType &max_elem) {
+    min_elem = dataset_get(obj, ind[0], element);
+    max_elem = dataset_get(obj, ind[0], element);
+    for (IndexType i = 1; i < count; ++i) {
+      ElementType val = dataset_get(obj, ind[i], element);
+      if (val < min_elem)
+        min_elem = val;
+      if (val > max_elem)
+        max_elem = val;
+    }
+  }
+
+  /**
+   * Create a tree node that subdivides the list of vecs from vind[first]
+   * to vind[last].  The routine is called recursively on each sublist.
+   *
+   * @param left index of the first vector
+   * @param right index of the last vector
+   */
+  NodePtr divideTree(Derived &obj, const IndexType left, const IndexType right,
+                     BoundingBox &bbox) {
+    NodePtr node = obj.pool.template allocate<Node>(); // allocate memory
+
+    /* If too few exemplars remain, then make this a leaf node. */
+    if ((right - left) <= static_cast<IndexType>(obj.m_leaf_max_size)) {
+      node->child1 = node->child2 = NULL; /* Mark as leaf node. */
+      node->node_type.lr.left = left;
+      node->node_type.lr.right = right;
+
+      // compute bounding-box of leaf points
+      for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+        bbox[i].low = dataset_get(obj, obj.vind[left], i);
+        bbox[i].high = dataset_get(obj, obj.vind[left], i);
+      }
+      for (IndexType k = left + 1; k < right; ++k) {
+        for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+          if (bbox[i].low > dataset_get(obj, obj.vind[k], i))
+            bbox[i].low = dataset_get(obj, obj.vind[k], i);
+          if (bbox[i].high < dataset_get(obj, obj.vind[k], i))
+            bbox[i].high = dataset_get(obj, obj.vind[k], i);
+        }
+      }
+    } else {
+      IndexType idx;
+      int cutfeat;
+      DistanceType cutval;
+      middleSplit_(obj, &obj.vind[0] + left, right - left, idx, cutfeat, cutval,
+                   bbox);
+
+      node->node_type.sub.divfeat = cutfeat;
+
+      BoundingBox left_bbox(bbox);
+      left_bbox[cutfeat].high = cutval;
+      node->child1 = divideTree(obj, left, left + idx, left_bbox);
+
+      BoundingBox right_bbox(bbox);
+      right_bbox[cutfeat].low = cutval;
+      node->child2 = divideTree(obj, left + idx, right, right_bbox);
+
+      node->node_type.sub.divlow = left_bbox[cutfeat].high;
+      node->node_type.sub.divhigh = right_bbox[cutfeat].low;
+
+      for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+        bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low);
+        bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high);
+      }
+    }
+
+    return node;
+  }
+
+  void middleSplit_(Derived &obj, IndexType *ind, IndexType count,
+                    IndexType &index, int &cutfeat, DistanceType &cutval,
+                    const BoundingBox &bbox) {
+    const DistanceType EPS = static_cast<DistanceType>(0.00001);
+    ElementType max_span = bbox[0].high - bbox[0].low;
+    for (int i = 1; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+      ElementType span = bbox[i].high - bbox[i].low;
+      if (span > max_span) {
+        max_span = span;
+      }
+    }
+    ElementType max_spread = -1;
+    cutfeat = 0;
+    for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+      ElementType span = bbox[i].high - bbox[i].low;
+      if (span > (1 - EPS) * max_span) {
+        ElementType min_elem, max_elem;
+        computeMinMax(obj, ind, count, i, min_elem, max_elem);
+        ElementType spread = max_elem - min_elem;
+        if (spread > max_spread) {
+          cutfeat = i;
+          max_spread = spread;
+        }
+      }
+    }
+    // split in the middle
+    DistanceType split_val = (bbox[cutfeat].low + bbox[cutfeat].high) / 2;
+    ElementType min_elem, max_elem;
+    computeMinMax(obj, ind, count, cutfeat, min_elem, max_elem);
+
+    if (split_val < min_elem)
+      cutval = min_elem;
+    else if (split_val > max_elem)
+      cutval = max_elem;
+    else
+      cutval = split_val;
+
+    IndexType lim1, lim2;
+    planeSplit(obj, ind, count, cutfeat, cutval, lim1, lim2);
+
+    if (lim1 > count / 2)
+      index = lim1;
+    else if (lim2 < count / 2)
+      index = lim2;
+    else
+      index = count / 2;
+  }
+
+  /**
+   *  Subdivide the list of points by a plane perpendicular on axe corresponding
+   *  to the 'cutfeat' dimension at 'cutval' position.
+   *
+   *  On return:
+   *  dataset[ind[0..lim1-1]][cutfeat]<cutval
+   *  dataset[ind[lim1..lim2-1]][cutfeat]==cutval
+   *  dataset[ind[lim2..count]][cutfeat]>cutval
+   */
+  void planeSplit(Derived &obj, IndexType *ind, const IndexType count,
+                  int cutfeat, DistanceType &cutval, IndexType &lim1,
+                  IndexType &lim2) {
+    /* Move vector indices for left subtree to front of list. */
+    IndexType left = 0;
+    IndexType right = count - 1;
+    for (;;) {
+      while (left <= right && dataset_get(obj, ind[left], cutfeat) < cutval)
+        ++left;
+      while (right && left <= right &&
+             dataset_get(obj, ind[right], cutfeat) >= cutval)
+        --right;
+      if (left > right || !right)
+        break; // "!right" was added to support unsigned Index types
+      std::swap(ind[left], ind[right]);
+      ++left;
+      --right;
+    }
+    /* If either list is empty, it means that all remaining features
+     * are identical. Split in the middle to maintain a balanced tree.
+     */
+    lim1 = left;
+    right = count - 1;
+    for (;;) {
+      while (left <= right && dataset_get(obj, ind[left], cutfeat) <= cutval)
+        ++left;
+      while (right && left <= right &&
+             dataset_get(obj, ind[right], cutfeat) > cutval)
+        --right;
+      if (left > right || !right)
+        break; // "!right" was added to support unsigned Index types
+      std::swap(ind[left], ind[right]);
+      ++left;
+      --right;
+    }
+    lim2 = left;
+  }
+
+  DistanceType computeInitialDistances(const Derived &obj,
+                                       const ElementType *vec,
+                                       distance_vector_t &dists) const {
+    assert(vec);
+    DistanceType distsq = DistanceType();
+
+    for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) {
+      if (vec[i] < obj.root_bbox[i].low) {
+        dists[i] = obj.distance.accum_dist(vec[i], obj.root_bbox[i].low, i);
+        distsq += dists[i];
+      }
+      if (vec[i] > obj.root_bbox[i].high) {
+        dists[i] = obj.distance.accum_dist(vec[i], obj.root_bbox[i].high, i);
+        distsq += dists[i];
+      }
+    }
+    return distsq;
+  }
+
+  void save_tree(Derived &obj, FILE *stream, NodePtr tree) {
+    save_value(stream, *tree);
+    if (tree->child1 != NULL) {
+      save_tree(obj, stream, tree->child1);
+    }
+    if (tree->child2 != NULL) {
+      save_tree(obj, stream, tree->child2);
+    }
+  }
+
+  void load_tree(Derived &obj, FILE *stream, NodePtr &tree) {
+    tree = obj.pool.template allocate<Node>();
+    load_value(stream, *tree);
+    if (tree->child1 != NULL) {
+      load_tree(obj, stream, tree->child1);
+    }
+    if (tree->child2 != NULL) {
+      load_tree(obj, stream, tree->child2);
+    }
+  }
+
+  /**  Stores the index in a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so when
+   * loading the index object it must be constructed associated to the same
+   * source of data points used while building it. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void saveIndex_(Derived &obj, FILE *stream) {
+    save_value(stream, obj.m_size);
+    save_value(stream, obj.dim);
+    save_value(stream, obj.root_bbox);
+    save_value(stream, obj.m_leaf_max_size);
+    save_value(stream, obj.vind);
+    save_tree(obj, stream, obj.root_node);
+  }
+
+  /**  Loads a previous index from a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so the
+   * index object must be constructed associated to the same source of data
+   * points used while building the index. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void loadIndex_(Derived &obj, FILE *stream) {
+    load_value(stream, obj.m_size);
+    load_value(stream, obj.dim);
+    load_value(stream, obj.root_bbox);
+    load_value(stream, obj.m_leaf_max_size);
+    load_value(stream, obj.vind);
+    load_tree(obj, stream, obj.root_node);
+  }
+};
+
+/** @addtogroup kdtrees_grp KD-tree classes and adaptors
+ * @{ */
+
+/** kd-tree static index
+ *
+ * Contains the k-d trees and other information for indexing a set of points
+ * for nearest-neighbor matching.
+ *
+ *  The class "DatasetAdaptor" must provide the following interface (can be
+ * non-virtual, inlined methods):
+ *
+ *  \code
+ *   // Must return the number of data poins
+ *   inline size_t kdtree_get_point_count() const { ... }
+ *
+ *
+ *   // Must return the dim'th component of the idx'th point in the class:
+ *   inline T kdtree_get_pt(const size_t idx, const size_t dim) const { ... }
+ *
+ *   // Optional bounding-box computation: return false to default to a standard
+ * bbox computation loop.
+ *   //   Return true if the BBOX was already computed by the class and returned
+ * in "bb" so it can be avoided to redo it again.
+ *   //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3
+ * for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const
+ *   {
+ *      bb[0].low = ...; bb[0].high = ...;  // 0th dimension limits
+ *      bb[1].low = ...; bb[1].high = ...;  // 1st dimension limits
+ *      ...
+ *      return true;
+ *   }
+ *
+ *  \endcode
+ *
+ * \tparam DatasetAdaptor The user-provided adaptor (see comments above).
+ * \tparam Distance The distance metric to use: nanoflann::metric_L1,
+ * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM
+ * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will
+ * be typically size_t or int
+ */
+template <typename Distance, class DatasetAdaptor, int DIM = -1,
+          typename IndexType = size_t>
+class KDTreeSingleIndexAdaptor
+    : public KDTreeBaseClass<
+          KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType>,
+          Distance, DatasetAdaptor, DIM, IndexType> {
+public:
+  /** Deleted copy constructor*/
+  KDTreeSingleIndexAdaptor(
+      const KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType>
+          &) = delete;
+
+  /**
+   * The dataset used by this index
+   */
+  const DatasetAdaptor &dataset; //!< The source of our data
+
+  const KDTreeSingleIndexAdaptorParams index_params;
+
+  Distance distance;
+
+  typedef typename nanoflann::KDTreeBaseClass<
+      nanoflann::KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM,
+                                          IndexType>,
+      Distance, DatasetAdaptor, DIM, IndexType>
+      BaseClassRef;
+
+  typedef typename BaseClassRef::ElementType ElementType;
+  typedef typename BaseClassRef::DistanceType DistanceType;
+
+  typedef typename BaseClassRef::Node Node;
+  typedef Node *NodePtr;
+
+  typedef typename BaseClassRef::Interval Interval;
+  /** Define "BoundingBox" as a fixed-size or variable-size container depending
+   * on "DIM" */
+  typedef typename BaseClassRef::BoundingBox BoundingBox;
+
+  /** Define "distance_vector_t" as a fixed-size or variable-size container
+   * depending on "DIM" */
+  typedef typename BaseClassRef::distance_vector_t distance_vector_t;
+
+  /**
+   * KDTree constructor
+   *
+   * Refer to docs in README.md or online in
+   * https://github.com/jlblancoc/nanoflann
+   *
+   * The KD-Tree point dimension (the length of each point in the datase, e.g. 3
+   * for 3D points) is determined by means of:
+   *  - The \a DIM template parameter if >0 (highest priority)
+   *  - Otherwise, the \a dimensionality parameter of this constructor.
+   *
+   * @param inputData Dataset with the input features
+   * @param params Basically, the maximum leaf node size
+   */
+  KDTreeSingleIndexAdaptor(const int dimensionality,
+                           const DatasetAdaptor &inputData,
+                           const KDTreeSingleIndexAdaptorParams &params =
+                               KDTreeSingleIndexAdaptorParams())
+      : dataset(inputData), index_params(params), distance(inputData) {
+    BaseClassRef::root_node = NULL;
+    BaseClassRef::m_size = dataset.kdtree_get_point_count();
+    BaseClassRef::m_size_at_index_build = BaseClassRef::m_size;
+    BaseClassRef::dim = dimensionality;
+    if (DIM > 0)
+      BaseClassRef::dim = DIM;
+    BaseClassRef::m_leaf_max_size = params.leaf_max_size;
+
+    // Create a permutable array of indices to the input vectors.
+    init_vind();
+  }
+
+  /**
+   * Builds the index
+   */
+  void buildIndex() {
+    BaseClassRef::m_size = dataset.kdtree_get_point_count();
+    BaseClassRef::m_size_at_index_build = BaseClassRef::m_size;
+    init_vind();
+    this->freeIndex(*this);
+    BaseClassRef::m_size_at_index_build = BaseClassRef::m_size;
+    if (BaseClassRef::m_size == 0)
+      return;
+    computeBoundingBox(BaseClassRef::root_bbox);
+    BaseClassRef::root_node =
+        this->divideTree(*this, 0, BaseClassRef::m_size,
+                         BaseClassRef::root_bbox); // construct the tree
+  }
+
+  /** \name Query methods
+   * @{ */
+
+  /**
+   * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored
+   * inside the result object.
+   *
+   * Params:
+   *     result = the result object in which the indices of the
+   * nearest-neighbors are stored vec = the vector for which to search the
+   * nearest neighbors
+   *
+   * \tparam RESULTSET Should be any ResultSet<DistanceType>
+   * \return  True if the requested neighbors could be found.
+   * \sa knnSearch, radiusSearch
+   */
+  template <typename RESULTSET>
+  bool findNeighbors(RESULTSET &result, const ElementType *vec,
+                     const SearchParams &searchParams) const {
+    assert(vec);
+    if (this->size(*this) == 0)
+      return false;
+    if (!BaseClassRef::root_node)
+      throw std::runtime_error(
+          "[nanoflann] findNeighbors() called before building the index.");
+    float epsError = 1 + searchParams.eps;
+
+    distance_vector_t
+        dists; // fixed or variable-sized container (depending on DIM)
+    auto zero = static_cast<decltype(result.worstDist())>(0);
+    assign(dists, (DIM > 0 ? DIM : BaseClassRef::dim),
+           zero); // Fill it with zeros.
+    DistanceType distsq = this->computeInitialDistances(*this, vec, dists);
+    searchLevel(result, vec, BaseClassRef::root_node, distsq, dists,
+                epsError); // "count_leaf" parameter removed since was neither
+                           // used nor returned to the user.
+    return result.full();
+  }
+
+  /**
+   * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1].
+   * Their indices are stored inside the result object. \sa radiusSearch,
+   * findNeighbors \note nChecks_IGNORED is ignored but kept for compatibility
+   * with the original FLANN interface. \return Number `N` of valid points in
+   * the result set. Only the first `N` entries in `out_indices` and
+   * `out_distances_sq` will be valid. Return may be less than `num_closest`
+   * only if the number of elements in the tree is less than `num_closest`.
+   */
+  size_t knnSearch(const ElementType *query_point, const size_t num_closest,
+                   IndexType *out_indices, DistanceType *out_distances_sq,
+                   const int /* nChecks_IGNORED */ = 10) const {
+    nanoflann::KNNResultSet<DistanceType, IndexType> resultSet(num_closest);
+    resultSet.init(out_indices, out_distances_sq);
+    this->findNeighbors(resultSet, query_point, nanoflann::SearchParams());
+    return resultSet.size();
+  }
+
+  /**
+   * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius.
+   *  The output is given as a vector of pairs, of which the first element is a
+   * point index and the second the corresponding distance. Previous contents of
+   * \a IndicesDists are cleared.
+   *
+   *  If searchParams.sorted==true, the output list is sorted by ascending
+   * distances.
+   *
+   *  For a better performance, it is advisable to do a .reserve() on the vector
+   * if you have any wild guess about the number of expected matches.
+   *
+   *  \sa knnSearch, findNeighbors, radiusSearchCustomCallback
+   * \return The number of points within the given radius (i.e. indices.size()
+   * or dists.size() )
+   */
+  size_t
+  radiusSearch(const ElementType *query_point, const DistanceType &radius,
+               std::vector<std::pair<IndexType, DistanceType>> &IndicesDists,
+               const SearchParams &searchParams) const {
+    RadiusResultSet<DistanceType, IndexType> resultSet(radius, IndicesDists);
+    const size_t nFound =
+        radiusSearchCustomCallback(query_point, resultSet, searchParams);
+    if (searchParams.sorted)
+      std::sort(IndicesDists.begin(), IndicesDists.end(), IndexDist_Sorter());
+    return nFound;
+  }
+
+  /**
+   * Just like radiusSearch() but with a custom callback class for each point
+   * found in the radius of the query. See the source of RadiusResultSet<> as a
+   * start point for your own classes. \sa radiusSearch
+   */
+  template <class SEARCH_CALLBACK>
+  size_t radiusSearchCustomCallback(
+      const ElementType *query_point, SEARCH_CALLBACK &resultSet,
+      const SearchParams &searchParams = SearchParams()) const {
+    this->findNeighbors(resultSet, query_point, searchParams);
+    return resultSet.size();
+  }
+
+  /** @} */
+
+public:
+  /** Make sure the auxiliary list \a vind has the same size than the current
+   * dataset, and re-generate if size has changed. */
+  void init_vind() {
+    // Create a permutable array of indices to the input vectors.
+    BaseClassRef::m_size = dataset.kdtree_get_point_count();
+    if (BaseClassRef::vind.size() != BaseClassRef::m_size)
+      BaseClassRef::vind.resize(BaseClassRef::m_size);
+    for (size_t i = 0; i < BaseClassRef::m_size; i++)
+      BaseClassRef::vind[i] = i;
+  }
+
+  void computeBoundingBox(BoundingBox &bbox) {
+    resize(bbox, (DIM > 0 ? DIM : BaseClassRef::dim));
+    if (dataset.kdtree_get_bbox(bbox)) {
+      // Done! It was implemented in derived class
+    } else {
+      const size_t N = dataset.kdtree_get_point_count();
+      if (!N)
+        throw std::runtime_error("[nanoflann] computeBoundingBox() called but "
+                                 "no data points found.");
+      for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) {
+        bbox[i].low = bbox[i].high = this->dataset_get(*this, 0, i);
+      }
+      for (size_t k = 1; k < N; ++k) {
+        for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) {
+          if (this->dataset_get(*this, k, i) < bbox[i].low)
+            bbox[i].low = this->dataset_get(*this, k, i);
+          if (this->dataset_get(*this, k, i) > bbox[i].high)
+            bbox[i].high = this->dataset_get(*this, k, i);
+        }
+      }
+    }
+  }
+
+  /**
+   * Performs an exact search in the tree starting from a node.
+   * \tparam RESULTSET Should be any ResultSet<DistanceType>
+   * \return true if the search should be continued, false if the results are
+   * sufficient
+   */
+  template <class RESULTSET>
+  bool searchLevel(RESULTSET &result_set, const ElementType *vec,
+                   const NodePtr node, DistanceType mindistsq,
+                   distance_vector_t &dists, const float epsError) const {
+    /* If this is a leaf node, then do check and return. */
+    if ((node->child1 == NULL) && (node->child2 == NULL)) {
+      // count_leaf += (node->lr.right-node->lr.left);  // Removed since was
+      // neither used nor returned to the user.
+      DistanceType worst_dist = result_set.worstDist();
+      for (IndexType i = node->node_type.lr.left; i < node->node_type.lr.right;
+           ++i) {
+        const IndexType index = BaseClassRef::vind[i]; // reorder... : i;
+        DistanceType dist = distance.evalMetric(
+            vec, index, (DIM > 0 ? DIM : BaseClassRef::dim));
+        if (dist < worst_dist) {
+          if (!result_set.addPoint(dist, BaseClassRef::vind[i])) {
+            // the resultset doesn't want to receive any more points, we're done
+            // searching!
+            return false;
+          }
+        }
+      }
+      return true;
+    }
+
+    /* Which child branch should be taken first? */
+    int idx = node->node_type.sub.divfeat;
+    ElementType val = vec[idx];
+    DistanceType diff1 = val - node->node_type.sub.divlow;
+    DistanceType diff2 = val - node->node_type.sub.divhigh;
+
+    NodePtr bestChild;
+    NodePtr otherChild;
+    DistanceType cut_dist;
+    if ((diff1 + diff2) < 0) {
+      bestChild = node->child1;
+      otherChild = node->child2;
+      cut_dist = distance.accum_dist(val, node->node_type.sub.divhigh, idx);
+    } else {
+      bestChild = node->child2;
+      otherChild = node->child1;
+      cut_dist = distance.accum_dist(val, node->node_type.sub.divlow, idx);
+    }
+
+    /* Call recursively to search next level down. */
+    if (!searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError)) {
+      // the resultset doesn't want to receive any more points, we're done
+      // searching!
+      return false;
+    }
+
+    DistanceType dst = dists[idx];
+    mindistsq = mindistsq + cut_dist - dst;
+    dists[idx] = cut_dist;
+    if (mindistsq * epsError <= result_set.worstDist()) {
+      if (!searchLevel(result_set, vec, otherChild, mindistsq, dists,
+                       epsError)) {
+        // the resultset doesn't want to receive any more points, we're done
+        // searching!
+        return false;
+      }
+    }
+    dists[idx] = dst;
+    return true;
+  }
+
+public:
+  /**  Stores the index in a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so when
+   * loading the index object it must be constructed associated to the same
+   * source of data points used while building it. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void saveIndex(FILE *stream) { this->saveIndex_(*this, stream); }
+
+  /**  Loads a previous index from a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so the
+   * index object must be constructed associated to the same source of data
+   * points used while building the index. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void loadIndex(FILE *stream) { this->loadIndex_(*this, stream); }
+
+}; // class KDTree
+
+/** kd-tree dynamic index
+ *
+ * Contains the k-d trees and other information for indexing a set of points
+ * for nearest-neighbor matching.
+ *
+ *  The class "DatasetAdaptor" must provide the following interface (can be
+ * non-virtual, inlined methods):
+ *
+ *  \code
+ *   // Must return the number of data poins
+ *   inline size_t kdtree_get_point_count() const { ... }
+ *
+ *   // Must return the dim'th component of the idx'th point in the class:
+ *   inline T kdtree_get_pt(const size_t idx, const size_t dim) const { ... }
+ *
+ *   // Optional bounding-box computation: return false to default to a standard
+ * bbox computation loop.
+ *   //   Return true if the BBOX was already computed by the class and returned
+ * in "bb" so it can be avoided to redo it again.
+ *   //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3
+ * for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const
+ *   {
+ *      bb[0].low = ...; bb[0].high = ...;  // 0th dimension limits
+ *      bb[1].low = ...; bb[1].high = ...;  // 1st dimension limits
+ *      ...
+ *      return true;
+ *   }
+ *
+ *  \endcode
+ *
+ * \tparam DatasetAdaptor The user-provided adaptor (see comments above).
+ * \tparam Distance The distance metric to use: nanoflann::metric_L1,
+ * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM
+ * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will
+ * be typically size_t or int
+ */
+template <typename Distance, class DatasetAdaptor, int DIM = -1,
+          typename IndexType = size_t>
+class KDTreeSingleIndexDynamicAdaptor_
+    : public KDTreeBaseClass<KDTreeSingleIndexDynamicAdaptor_<
+                                 Distance, DatasetAdaptor, DIM, IndexType>,
+                             Distance, DatasetAdaptor, DIM, IndexType> {
+public:
+  /**
+   * The dataset used by this index
+   */
+  const DatasetAdaptor &dataset; //!< The source of our data
+
+  KDTreeSingleIndexAdaptorParams index_params;
+
+  std::vector<int> &treeIndex;
+
+  Distance distance;
+
+  typedef typename nanoflann::KDTreeBaseClass<
+      nanoflann::KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM,
+                                                  IndexType>,
+      Distance, DatasetAdaptor, DIM, IndexType>
+      BaseClassRef;
+
+  typedef typename BaseClassRef::ElementType ElementType;
+  typedef typename BaseClassRef::DistanceType DistanceType;
+
+  typedef typename BaseClassRef::Node Node;
+  typedef Node *NodePtr;
+
+  typedef typename BaseClassRef::Interval Interval;
+  /** Define "BoundingBox" as a fixed-size or variable-size container depending
+   * on "DIM" */
+  typedef typename BaseClassRef::BoundingBox BoundingBox;
+
+  /** Define "distance_vector_t" as a fixed-size or variable-size container
+   * depending on "DIM" */
+  typedef typename BaseClassRef::distance_vector_t distance_vector_t;
+
+  /**
+   * KDTree constructor
+   *
+   * Refer to docs in README.md or online in
+   * https://github.com/jlblancoc/nanoflann
+   *
+   * The KD-Tree point dimension (the length of each point in the datase, e.g. 3
+   * for 3D points) is determined by means of:
+   *  - The \a DIM template parameter if >0 (highest priority)
+   *  - Otherwise, the \a dimensionality parameter of this constructor.
+   *
+   * @param inputData Dataset with the input features
+   * @param params Basically, the maximum leaf node size
+   */
+  KDTreeSingleIndexDynamicAdaptor_(
+      const int dimensionality, const DatasetAdaptor &inputData,
+      std::vector<int> &treeIndex_,
+      const KDTreeSingleIndexAdaptorParams &params =
+          KDTreeSingleIndexAdaptorParams())
+      : dataset(inputData), index_params(params), treeIndex(treeIndex_),
+        distance(inputData) {
+    BaseClassRef::root_node = NULL;
+    BaseClassRef::m_size = 0;
+    BaseClassRef::m_size_at_index_build = 0;
+    BaseClassRef::dim = dimensionality;
+    if (DIM > 0)
+      BaseClassRef::dim = DIM;
+    BaseClassRef::m_leaf_max_size = params.leaf_max_size;
+  }
+
+  /** Assignment operator definiton */
+  KDTreeSingleIndexDynamicAdaptor_
+  operator=(const KDTreeSingleIndexDynamicAdaptor_ &rhs) {
+    KDTreeSingleIndexDynamicAdaptor_ tmp(rhs);
+    std::swap(BaseClassRef::vind, tmp.BaseClassRef::vind);
+    std::swap(BaseClassRef::m_leaf_max_size, tmp.BaseClassRef::m_leaf_max_size);
+    std::swap(index_params, tmp.index_params);
+    std::swap(treeIndex, tmp.treeIndex);
+    std::swap(BaseClassRef::m_size, tmp.BaseClassRef::m_size);
+    std::swap(BaseClassRef::m_size_at_index_build,
+              tmp.BaseClassRef::m_size_at_index_build);
+    std::swap(BaseClassRef::root_node, tmp.BaseClassRef::root_node);
+    std::swap(BaseClassRef::root_bbox, tmp.BaseClassRef::root_bbox);
+    std::swap(BaseClassRef::pool, tmp.BaseClassRef::pool);
+    return *this;
+  }
+
+  /**
+   * Builds the index
+   */
+  void buildIndex() {
+    BaseClassRef::m_size = BaseClassRef::vind.size();
+    this->freeIndex(*this);
+    BaseClassRef::m_size_at_index_build = BaseClassRef::m_size;
+    if (BaseClassRef::m_size == 0)
+      return;
+    computeBoundingBox(BaseClassRef::root_bbox);
+    BaseClassRef::root_node =
+        this->divideTree(*this, 0, BaseClassRef::m_size,
+                         BaseClassRef::root_bbox); // construct the tree
+  }
+
+  /** \name Query methods
+   * @{ */
+
+  /**
+   * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored
+   * inside the result object.
+   *
+   * Params:
+   *     result = the result object in which the indices of the
+   * nearest-neighbors are stored vec = the vector for which to search the
+   * nearest neighbors
+   *
+   * \tparam RESULTSET Should be any ResultSet<DistanceType>
+   * \return  True if the requested neighbors could be found.
+   * \sa knnSearch, radiusSearch
+   */
+  template <typename RESULTSET>
+  bool findNeighbors(RESULTSET &result, const ElementType *vec,
+                     const SearchParams &searchParams) const {
+    assert(vec);
+    if (this->size(*this) == 0)
+      return false;
+    if (!BaseClassRef::root_node)
+      return false;
+    float epsError = 1 + searchParams.eps;
+
+    // fixed or variable-sized container (depending on DIM)
+    distance_vector_t dists;
+    // Fill it with zeros.
+    assign(dists, (DIM > 0 ? DIM : BaseClassRef::dim),
+           static_cast<typename distance_vector_t::value_type>(0));
+    DistanceType distsq = this->computeInitialDistances(*this, vec, dists);
+    searchLevel(result, vec, BaseClassRef::root_node, distsq, dists,
+                epsError); // "count_leaf" parameter removed since was neither
+                           // used nor returned to the user.
+    return result.full();
+  }
+
+  /**
+   * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1].
+   * Their indices are stored inside the result object. \sa radiusSearch,
+   * findNeighbors \note nChecks_IGNORED is ignored but kept for compatibility
+   * with the original FLANN interface. \return Number `N` of valid points in
+   * the result set. Only the first `N` entries in `out_indices` and
+   * `out_distances_sq` will be valid. Return may be less than `num_closest`
+   * only if the number of elements in the tree is less than `num_closest`.
+   */
+  size_t knnSearch(const ElementType *query_point, const size_t num_closest,
+                   IndexType *out_indices, DistanceType *out_distances_sq,
+                   const int /* nChecks_IGNORED */ = 10) const {
+    nanoflann::KNNResultSet<DistanceType, IndexType> resultSet(num_closest);
+    resultSet.init(out_indices, out_distances_sq);
+    this->findNeighbors(resultSet, query_point, nanoflann::SearchParams());
+    return resultSet.size();
+  }
+
+  /**
+   * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius.
+   *  The output is given as a vector of pairs, of which the first element is a
+   * point index and the second the corresponding distance. Previous contents of
+   * \a IndicesDists are cleared.
+   *
+   *  If searchParams.sorted==true, the output list is sorted by ascending
+   * distances.
+   *
+   *  For a better performance, it is advisable to do a .reserve() on the vector
+   * if you have any wild guess about the number of expected matches.
+   *
+   *  \sa knnSearch, findNeighbors, radiusSearchCustomCallback
+   * \return The number of points within the given radius (i.e. indices.size()
+   * or dists.size() )
+   */
+  size_t
+  radiusSearch(const ElementType *query_point, const DistanceType &radius,
+               std::vector<std::pair<IndexType, DistanceType>> &IndicesDists,
+               const SearchParams &searchParams) const {
+    RadiusResultSet<DistanceType, IndexType> resultSet(radius, IndicesDists);
+    const size_t nFound =
+        radiusSearchCustomCallback(query_point, resultSet, searchParams);
+    if (searchParams.sorted)
+      std::sort(IndicesDists.begin(), IndicesDists.end(), IndexDist_Sorter());
+    return nFound;
+  }
+
+  /**
+   * Just like radiusSearch() but with a custom callback class for each point
+   * found in the radius of the query. See the source of RadiusResultSet<> as a
+   * start point for your own classes. \sa radiusSearch
+   */
+  template <class SEARCH_CALLBACK>
+  size_t radiusSearchCustomCallback(
+      const ElementType *query_point, SEARCH_CALLBACK &resultSet,
+      const SearchParams &searchParams = SearchParams()) const {
+    this->findNeighbors(resultSet, query_point, searchParams);
+    return resultSet.size();
+  }
+
+  /** @} */
+
+public:
+  void computeBoundingBox(BoundingBox &bbox) {
+    resize(bbox, (DIM > 0 ? DIM : BaseClassRef::dim));
+
+    if (dataset.kdtree_get_bbox(bbox)) {
+      // Done! It was implemented in derived class
+    } else {
+      const size_t N = BaseClassRef::m_size;
+      if (!N)
+        throw std::runtime_error("[nanoflann] computeBoundingBox() called but "
+                                 "no data points found.");
+      for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) {
+        bbox[i].low = bbox[i].high =
+            this->dataset_get(*this, BaseClassRef::vind[0], i);
+      }
+      for (size_t k = 1; k < N; ++k) {
+        for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) {
+          if (this->dataset_get(*this, BaseClassRef::vind[k], i) < bbox[i].low)
+            bbox[i].low = this->dataset_get(*this, BaseClassRef::vind[k], i);
+          if (this->dataset_get(*this, BaseClassRef::vind[k], i) > bbox[i].high)
+            bbox[i].high = this->dataset_get(*this, BaseClassRef::vind[k], i);
+        }
+      }
+    }
+  }
+
+  /**
+   * Performs an exact search in the tree starting from a node.
+   * \tparam RESULTSET Should be any ResultSet<DistanceType>
+   */
+  template <class RESULTSET>
+  void searchLevel(RESULTSET &result_set, const ElementType *vec,
+                   const NodePtr node, DistanceType mindistsq,
+                   distance_vector_t &dists, const float epsError) const {
+    /* If this is a leaf node, then do check and return. */
+    if ((node->child1 == NULL) && (node->child2 == NULL)) {
+      // count_leaf += (node->lr.right-node->lr.left);  // Removed since was
+      // neither used nor returned to the user.
+      DistanceType worst_dist = result_set.worstDist();
+      for (IndexType i = node->node_type.lr.left; i < node->node_type.lr.right;
+           ++i) {
+        const IndexType index = BaseClassRef::vind[i]; // reorder... : i;
+        if (treeIndex[index] == -1)
+          continue;
+        DistanceType dist = distance.evalMetric(
+            vec, index, (DIM > 0 ? DIM : BaseClassRef::dim));
+        if (dist < worst_dist) {
+          if (!result_set.addPoint(
+                  static_cast<typename RESULTSET::DistanceType>(dist),
+                  static_cast<typename RESULTSET::IndexType>(
+                      BaseClassRef::vind[i]))) {
+            // the resultset doesn't want to receive any more points, we're done
+            // searching!
+            return; // false;
+          }
+        }
+      }
+      return;
+    }
+
+    /* Which child branch should be taken first? */
+    int idx = node->node_type.sub.divfeat;
+    ElementType val = vec[idx];
+    DistanceType diff1 = val - node->node_type.sub.divlow;
+    DistanceType diff2 = val - node->node_type.sub.divhigh;
+
+    NodePtr bestChild;
+    NodePtr otherChild;
+    DistanceType cut_dist;
+    if ((diff1 + diff2) < 0) {
+      bestChild = node->child1;
+      otherChild = node->child2;
+      cut_dist = distance.accum_dist(val, node->node_type.sub.divhigh, idx);
+    } else {
+      bestChild = node->child2;
+      otherChild = node->child1;
+      cut_dist = distance.accum_dist(val, node->node_type.sub.divlow, idx);
+    }
+
+    /* Call recursively to search next level down. */
+    searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError);
+
+    DistanceType dst = dists[idx];
+    mindistsq = mindistsq + cut_dist - dst;
+    dists[idx] = cut_dist;
+    if (mindistsq * epsError <= result_set.worstDist()) {
+      searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError);
+    }
+    dists[idx] = dst;
+  }
+
+public:
+  /**  Stores the index in a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so when
+   * loading the index object it must be constructed associated to the same
+   * source of data points used while building it. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void saveIndex(FILE *stream) { this->saveIndex_(*this, stream); }
+
+  /**  Loads a previous index from a binary file.
+   *   IMPORTANT NOTE: The set of data points is NOT stored in the file, so the
+   * index object must be constructed associated to the same source of data
+   * points used while building the index. See the example:
+   * examples/saveload_example.cpp \sa loadIndex  */
+  void loadIndex(FILE *stream) { this->loadIndex_(*this, stream); }
+};
+
+/** kd-tree dynaimic index
+ *
+ * class to create multiple static index and merge their results to behave as
+ * single dynamic index as proposed in Logarithmic Approach.
+ *
+ *  Example of usage:
+ *  examples/dynamic_pointcloud_example.cpp
+ *
+ * \tparam DatasetAdaptor The user-provided adaptor (see comments above).
+ * \tparam Distance The distance metric to use: nanoflann::metric_L1,
+ * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM
+ * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will
+ * be typically size_t or int
+ */
+template <typename Distance, class DatasetAdaptor, int DIM = -1,
+          typename IndexType = size_t>
+class KDTreeSingleIndexDynamicAdaptor {
+public:
+  typedef typename Distance::ElementType ElementType;
+  typedef typename Distance::DistanceType DistanceType;
+
+protected:
+  size_t m_leaf_max_size;
+  size_t treeCount;
+  size_t pointCount;
+
+  /**
+   * The dataset used by this index
+   */
+  const DatasetAdaptor &dataset; //!< The source of our data
+
+  std::vector<int> treeIndex; //!< treeIndex[idx] is the index of tree in which
+                              //!< point at idx is stored. treeIndex[idx]=-1
+                              //!< means that point has been removed.
+
+  KDTreeSingleIndexAdaptorParams index_params;
+
+  int dim; //!< Dimensionality of each data point
+
+  typedef KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM>
+      index_container_t;
+  std::vector<index_container_t> index;
+
+public:
+  /** Get a const ref to the internal list of indices; the number of indices is
+   * adapted dynamically as the dataset grows in size. */
+  const std::vector<index_container_t> &getAllIndices() const { return index; }
+
+private:
+  /** finds position of least significant unset bit */
+  int First0Bit(IndexType num) {
+    int pos = 0;
+    while (num & 1) {
+      num = num >> 1;
+      pos++;
+    }
+    return pos;
+  }
+
+  /** Creates multiple empty trees to handle dynamic support */
+  void init() {
+    typedef KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM>
+        my_kd_tree_t;
+    std::vector<my_kd_tree_t> index_(
+        treeCount, my_kd_tree_t(dim /*dim*/, dataset, treeIndex, index_params));
+    index = index_;
+  }
+
+public:
+  Distance distance;
+
+  /**
+   * KDTree constructor
+   *
+   * Refer to docs in README.md or online in
+   * https://github.com/jlblancoc/nanoflann
+   *
+   * The KD-Tree point dimension (the length of each point in the datase, e.g. 3
+   * for 3D points) is determined by means of:
+   *  - The \a DIM template parameter if >0 (highest priority)
+   *  - Otherwise, the \a dimensionality parameter of this constructor.
+   *
+   * @param inputData Dataset with the input features
+   * @param params Basically, the maximum leaf node size
+   */
+  KDTreeSingleIndexDynamicAdaptor(const int dimensionality,
+                                  const DatasetAdaptor &inputData,
+                                  const KDTreeSingleIndexAdaptorParams &params =
+                                      KDTreeSingleIndexAdaptorParams(),
+                                  const size_t maximumPointCount = 1000000000U)
+      : dataset(inputData), index_params(params), distance(inputData) {
+    treeCount = static_cast<size_t>(std::log2(maximumPointCount));
+    pointCount = 0U;
+    dim = dimensionality;
+    treeIndex.clear();
+    if (DIM > 0)
+      dim = DIM;
+    m_leaf_max_size = params.leaf_max_size;
+    init();
+    const size_t num_initial_points = dataset.kdtree_get_point_count();
+    if (num_initial_points > 0) {
+      addPoints(0, num_initial_points - 1);
+    }
+  }
+
+  /** Deleted copy constructor*/
+  KDTreeSingleIndexDynamicAdaptor(
+      const KDTreeSingleIndexDynamicAdaptor<Distance, DatasetAdaptor, DIM,
+                                            IndexType> &) = delete;
+
+  /** Add points to the set, Inserts all points from [start, end] */
+  void addPoints(IndexType start, IndexType end) {
+    size_t count = end - start + 1;
+    treeIndex.resize(treeIndex.size() + count);
+    for (IndexType idx = start; idx <= end; idx++) {
+      int pos = First0Bit(pointCount);
+      index[pos].vind.clear();
+      treeIndex[pointCount] = pos;
+      for (int i = 0; i < pos; i++) {
+        for (int j = 0; j < static_cast<int>(index[i].vind.size()); j++) {
+          index[pos].vind.push_back(index[i].vind[j]);
+          if (treeIndex[index[i].vind[j]] != -1)
+            treeIndex[index[i].vind[j]] = pos;
+        }
+        index[i].vind.clear();
+        index[i].freeIndex(index[i]);
+      }
+      index[pos].vind.push_back(idx);
+      index[pos].buildIndex();
+      pointCount++;
+    }
+  }
+
+  /** Remove a point from the set (Lazy Deletion) */
+  void removePoint(size_t idx) {
+    if (idx >= pointCount)
+      return;
+    treeIndex[idx] = -1;
+  }
+
+  /**
+   * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored
+   * inside the result object.
+   *
+   * Params:
+   *     result = the result object in which the indices of the
+   * nearest-neighbors are stored vec = the vector for which to search the
+   * nearest neighbors
+   *
+   * \tparam RESULTSET Should be any ResultSet<DistanceType>
+   * \return  True if the requested neighbors could be found.
+   * \sa knnSearch, radiusSearch
+   */
+  template <typename RESULTSET>
+  bool findNeighbors(RESULTSET &result, const ElementType *vec,
+                     const SearchParams &searchParams) const {
+    for (size_t i = 0; i < treeCount; i++) {
+      index[i].findNeighbors(result, &vec[0], searchParams);
+    }
+    return result.full();
+  }
+};
+
+/** An L2-metric KD-tree adaptor for working with data directly stored in an
+ * Eigen Matrix, without duplicating the data storage. You can select whether a
+ * row or column in the matrix represents a point in the state space.
+ *
+ *  Example of usage:
+ * \code
+ * 	Eigen::Matrix<num_t,Dynamic,Dynamic>  mat;
+ * 	// Fill out "mat"...
+ *
+ * 	typedef KDTreeEigenMatrixAdaptor< Eigen::Matrix<num_t,Dynamic,Dynamic> >
+ * my_kd_tree_t; const int max_leaf = 10; my_kd_tree_t   mat_index(mat, max_leaf
+ * ); mat_index.index->buildIndex(); mat_index.index->... \endcode
+ *
+ *  \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality
+ * for the points in the data set, allowing more compiler optimizations. \tparam
+ * Distance The distance metric to use: nanoflann::metric_L1,
+ * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam row_major
+ * If set to true the rows of the matrix are used as the points, if set to false
+ * the columns of the matrix are used as the points.
+ */
+template <class MatrixType, int DIM = -1, class Distance = nanoflann::metric_L2,
+	  bool row_major = true>
+struct KDTreeEigenMatrixAdaptor {
+  typedef KDTreeEigenMatrixAdaptor<MatrixType, DIM, Distance, row_major> self_t;
+  typedef typename MatrixType::Scalar num_t;
+  typedef typename MatrixType::Index IndexType;
+  typedef
+      typename Distance::template traits<num_t, self_t>::distance_t metric_t;
+  typedef KDTreeSingleIndexAdaptor<metric_t, self_t,
+                                   MatrixType::ColsAtCompileTime, IndexType>
+      index_t;
+
+  index_t *index; //! The kd-tree index for the user to call its methods as
+                  //! usual with any other FLANN index.
+
+  /// Constructor: takes a const ref to the matrix object with the data points
+  KDTreeEigenMatrixAdaptor(const size_t dimensionality,
+                           const std::reference_wrapper<const MatrixType> &mat,
+                           const int leaf_max_size = 10)
+      : m_data_matrix(mat) {
+    const auto dims = row_major ? mat.get().cols() : mat.get().rows();
+    if (size_t(dims) != dimensionality)
+      throw std::runtime_error(
+          "Error: 'dimensionality' must match column count in data matrix");
+    if (DIM > 0 && int(dims) != DIM)
+      throw std::runtime_error(
+          "Data set dimensionality does not match the 'DIM' template argument");
+    index =
+        new index_t(static_cast<int>(dims), *this /* adaptor */,
+                    nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size));
+    index->buildIndex();
+  }
+
+public:
+  /** Deleted copy constructor */
+  KDTreeEigenMatrixAdaptor(const self_t &) = delete;
+
+  ~KDTreeEigenMatrixAdaptor() { delete index; }
+
+  const std::reference_wrapper<const MatrixType> m_data_matrix;
+
+  /** Query for the \a num_closest closest points to a given point (entered as
+   * query_point[0:dim-1]). Note that this is a short-cut method for
+   * index->findNeighbors(). The user can also call index->... methods as
+   * desired. \note nChecks_IGNORED is ignored but kept for compatibility with
+   * the original FLANN interface.
+   */
+  inline void query(const num_t *query_point, const size_t num_closest,
+                    IndexType *out_indices, num_t *out_distances_sq,
+                    const int /* nChecks_IGNORED */ = 10) const {
+    nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest);
+    resultSet.init(out_indices, out_distances_sq);
+    index->findNeighbors(resultSet, query_point, nanoflann::SearchParams());
+  }
+
+  /** @name Interface expected by KDTreeSingleIndexAdaptor
+   * @{ */
+
+  const self_t &derived() const { return *this; }
+  self_t &derived() { return *this; }
+
+  // Must return the number of data points
+  inline size_t kdtree_get_point_count() const {
+    if(row_major)
+      return m_data_matrix.get().rows();
+    else
+      return m_data_matrix.get().cols();
+  }
+
+  // Returns the dim'th component of the idx'th point in the class:
+  inline num_t kdtree_get_pt(const IndexType idx, size_t dim) const {
+    if(row_major)
+      return m_data_matrix.get().coeff(idx, IndexType(dim));
+    else
+      return m_data_matrix.get().coeff(IndexType(dim), idx);
+  }
+
+  // Optional bounding-box computation: return false to default to a standard
+  // bbox computation loop.
+  //   Return true if the BBOX was already computed by the class and returned in
+  //   "bb" so it can be avoided to redo it again. Look at bb.size() to find out
+  //   the expected dimensionality (e.g. 2 or 3 for point clouds)
+  template <class BBOX> bool kdtree_get_bbox(BBOX & /*bb*/) const {
+    return false;
+  }
+
+  /** @} */
+
+}; // end of KDTreeEigenMatrixAdaptor
+   /** @} */
+
+/** @} */ // end of grouping
+} // namespace nanoflann
+
+#endif /* NANOFLANN_HPP_ */

+ 119 - 0
include/nano_gicp/lsq_registration.hpp

@@ -0,0 +1,119 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_GICP_LSQ_REGISTRATION_HPP
+#define NANO_GICP_LSQ_REGISTRATION_HPP
+
+#include <Eigen/Core>
+#include <Eigen/Geometry>
+
+#include <pcl/point_types.h>
+#include <pcl/point_cloud.h>
+#include <pcl/registration/registration.h>
+
+namespace nano_gicp {
+
+enum class LSQ_OPTIMIZER_TYPE { GaussNewton, LevenbergMarquardt };
+
+template<typename PointSource, typename PointTarget>
+class LsqRegistration : public pcl::Registration<PointSource, PointTarget, float> {
+public:
+  using Scalar = float;
+  using Matrix4 = typename pcl::Registration<PointSource, PointTarget, Scalar>::Matrix4;
+
+  using PointCloudSource = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudSource;
+  using PointCloudSourcePtr = typename PointCloudSource::Ptr;
+  using PointCloudSourceConstPtr = typename PointCloudSource::ConstPtr;
+
+  using PointCloudTarget = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudTarget;
+  using PointCloudTargetPtr = typename PointCloudTarget::Ptr;
+  using PointCloudTargetConstPtr = typename PointCloudTarget::ConstPtr;
+
+protected:
+  using pcl::Registration<PointSource, PointTarget, Scalar>::input_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::nr_iterations_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::max_iterations_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::final_transformation_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::transformation_epsilon_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::converged_;
+
+public:
+  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
+
+  LsqRegistration();
+  virtual ~LsqRegistration();
+
+  void setRotationEpsilon(double eps);
+  void setInitialLambdaFactor(double init_lambda_factor);
+  void setDebugPrint(bool lm_debug_print);
+
+  const Eigen::Matrix<double, 6, 6>& getFinalHessian() const;
+
+  virtual void swapSourceAndTarget() {}
+  virtual void clearSource() {}
+  virtual void clearTarget() {}
+
+protected:
+  virtual void computeTransformation(PointCloudSource& output, const Matrix4& guess) override;
+
+  bool is_converged(const Eigen::Isometry3d& delta) const;
+
+  virtual double linearize(const Eigen::Isometry3d& trans, Eigen::Matrix<double, 6, 6>* H = nullptr, Eigen::Matrix<double, 6, 1>* b = nullptr) = 0;
+  virtual double compute_error(const Eigen::Isometry3d& trans) = 0;
+
+  bool step_optimize(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta);
+  bool step_gn(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta);
+  bool step_lm(Eigen::Isometry3d& x0, Eigen::Isometry3d& delta);
+
+protected:
+  double rotation_epsilon_;
+
+  LSQ_OPTIMIZER_TYPE lsq_optimizer_type_;
+  int lm_max_iterations_;
+  double lm_init_lambda_factor_;
+  double lm_lambda_;
+  bool lm_debug_print_;
+
+  Eigen::Matrix<double, 6, 6> final_hessian_;
+};
+}  // namespace nano_gicp
+
+#endif

+ 137 - 0
include/nano_gicp/nano_gicp.hpp

@@ -0,0 +1,137 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_GICP_NANO_GICP_HPP
+#define NANO_GICP_NANO_GICP_HPP
+
+#include <Eigen/Core>
+#include <Eigen/Geometry>
+
+#include <pcl/point_types.h>
+#include <pcl/point_cloud.h>
+#include <pcl/registration/registration.h>
+
+#include <nano_gicp/lsq_registration.hpp>
+#include <nano_gicp/gicp/gicp_settings.hpp>
+#include <nano_gicp/nanoflann.hpp>
+
+namespace nano_gicp {
+
+template<typename PointSource, typename PointTarget>
+class NanoGICP : public LsqRegistration<PointSource, PointTarget> {
+public:
+  using Scalar = float;
+  using Matrix4 = typename pcl::Registration<PointSource, PointTarget, Scalar>::Matrix4;
+
+  using PointCloudSource = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudSource;
+  using PointCloudSourcePtr = typename PointCloudSource::Ptr;
+  using PointCloudSourceConstPtr = typename PointCloudSource::ConstPtr;
+
+  using PointCloudTarget = typename pcl::Registration<PointSource, PointTarget, Scalar>::PointCloudTarget;
+  using PointCloudTargetPtr = typename PointCloudTarget::Ptr;
+  using PointCloudTargetConstPtr = typename PointCloudTarget::ConstPtr;
+
+protected:
+  using pcl::Registration<PointSource, PointTarget, Scalar>::reg_name_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::input_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::target_;
+  using pcl::Registration<PointSource, PointTarget, Scalar>::corr_dist_threshold_;
+
+public:
+  NanoGICP();
+  virtual ~NanoGICP() override;
+
+  void setNumThreads(int n);
+  void setCorrespondenceRandomness(int k);
+  void setRegularizationMethod(RegularizationMethod method);
+
+  virtual void swapSourceAndTarget() override;
+  virtual void clearSource() override;
+  virtual void clearTarget() override;
+
+  virtual void setInputSource(const PointCloudSourceConstPtr& cloud) override;
+  virtual void setSourceCovariances(const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covs);
+  virtual void setInputTarget(const PointCloudTargetConstPtr& cloud) override;
+  virtual void setTargetCovariances(const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covs);
+
+  virtual void registerInputSource(const PointCloudSourceConstPtr& cloud);
+
+  const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& getSourceCovariances() const {
+    return source_covs_;
+  }
+
+  const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& getTargetCovariances() const {
+    return target_covs_;
+  }
+
+protected:
+  virtual void computeTransformation(PointCloudSource& output, const Matrix4& guess) override;
+
+  virtual void update_correspondences(const Eigen::Isometry3d& trans);
+
+  virtual double linearize(const Eigen::Isometry3d& trans, Eigen::Matrix<double, 6, 6>* H, Eigen::Matrix<double, 6, 1>* b) override;
+
+  virtual double compute_error(const Eigen::Isometry3d& trans) override;
+
+  template<typename PointT>
+  bool calculate_covariances(const typename pcl::PointCloud<PointT>::ConstPtr& cloud, nanoflann::KdTreeFLANN<PointT>& kdtree, std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covariances);
+
+public:
+  std::shared_ptr<nanoflann::KdTreeFLANN<PointSource>> source_kdtree_;
+  std::shared_ptr<nanoflann::KdTreeFLANN<PointTarget>> target_kdtree_;
+
+  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> source_covs_;
+  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> target_covs_;
+
+protected:
+  int num_threads_;
+  int k_correspondences_;
+
+  RegularizationMethod regularization_method_;
+
+  std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> mahalanobis_;
+
+  std::vector<int> correspondences_;
+  std::vector<float> sq_distances_;
+};
+}  // namespace nano_gicp
+
+#endif

+ 196 - 0
include/nano_gicp/nanoflann.hpp

@@ -0,0 +1,196 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ * Copyright 2011-2021  Jose Luis Blanco (joseluisblancoc@gmail.com).
+ *   All rights reserved.
+ *
+ * THE BSD LICENSE
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef NANO_KDTREE_KDTREE_FLANN_H_
+#define NANO_KDTREE_KDTREE_FLANN_H_
+
+#include <boost/shared_ptr.hpp>
+#include <pcl/point_cloud.h>
+#include <pcl/point_types.h>
+#include <pcl/kdtree/kdtree_flann.h>
+#include "nano_gicp/impl/nanoflann_impl.hpp"
+
+namespace nanoflann
+{
+
+template <typename PointT>
+class KdTreeFLANN
+{
+public:
+
+  typedef typename pcl::PointCloud<PointT> PointCloud;
+  typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
+  typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
+
+  typedef boost::shared_ptr<KdTreeFLANN<PointT>> Ptr;
+  typedef boost::shared_ptr<const KdTreeFLANN<PointT>> ConstPtr;
+  typedef boost::shared_ptr<std::vector<int>> IndicesPtr;
+  typedef boost::shared_ptr<const std::vector<int>> IndicesConstPtr;
+
+  KdTreeFLANN (bool sorted = false);
+  KdTreeFLANN (const KdTreeFLANN<PointT> &k);
+
+  void  setEpsilon (float eps);
+
+  void  setSortedResults (bool sorted);
+
+  inline Ptr makeShared () { return Ptr (new KdTreeFLANN<PointT> (*this)); }
+
+  void setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices = IndicesConstPtr ());
+
+  inline PointCloudConstPtr getInputCloud() const { return _adaptor.pcl; }
+
+  int  nearestKSearch (const PointT &point, int k, std::vector<int> &k_indices,
+                       std::vector<float> &k_sqr_distances) const;
+
+  int radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
+                    std::vector<float> &k_sqr_distances) const;
+
+protected:
+
+  nanoflann::SearchParams _params;
+
+  struct PointCloud_Adaptor
+  {
+    inline size_t kdtree_get_point_count() const;
+    inline float kdtree_get_pt(const size_t idx, int dim) const;
+    template <class BBOX> bool kdtree_get_bbox(BBOX&) const { return false; }
+    PointCloudConstPtr pcl;
+    IndicesConstPtr indices;
+  };
+
+  typedef nanoflann::KDTreeSingleIndexAdaptor<
+    nanoflann::SO3_Adaptor<float, PointCloud_Adaptor > ,
+    PointCloud_Adaptor, 3, int> KDTreeFlann_PCL_SO3;
+
+  PointCloud_Adaptor _adaptor;
+
+  KDTreeFlann_PCL_SO3 _kdtree;
+
+};
+
+//---------- Definitions ---------------------
+
+template<typename PointT> inline
+KdTreeFLANN<PointT>::KdTreeFLANN(bool sorted):
+  _kdtree(3,_adaptor, KDTreeSingleIndexAdaptorParams(100))
+{
+  _params.sorted = sorted;
+}
+
+template<typename PointT> inline
+void KdTreeFLANN<PointT>::setEpsilon(float eps)
+{
+  _params.eps = eps;
+}
+
+template<typename PointT> inline
+void KdTreeFLANN<PointT>::setSortedResults(bool sorted)
+{
+  _params.sorted = sorted;
+}
+
+template<typename PointT> inline
+void KdTreeFLANN<PointT>::setInputCloud(const KdTreeFLANN::PointCloudConstPtr &cloud,
+                                        const IndicesConstPtr &indices)
+{
+  _adaptor.pcl = cloud;
+  _adaptor.indices = indices;
+  _kdtree.buildIndex();
+}
+
+template<typename PointT> inline
+int KdTreeFLANN<PointT>::nearestKSearch(const PointT &point, int num_closest,
+                                std::vector<int> &k_indices,
+                                std::vector<float> &k_sqr_distances) const
+{
+  k_indices.resize(num_closest);
+  k_sqr_distances.resize(num_closest);
+
+  nanoflann::KNNResultSet<float,int> resultSet(num_closest);
+  resultSet.init( k_indices.data(), k_sqr_distances.data());
+  _kdtree.findNeighbors(resultSet, point.data, nanoflann::SearchParams() );
+  return resultSet.size();
+}
+
+template<typename PointT> inline
+int KdTreeFLANN<PointT>::radiusSearch(const PointT &point, double radius,
+                              std::vector<int> &k_indices,
+                              std::vector<float> &k_sqr_distances) const
+{
+  static std::vector<std::pair<int, float> > indices_dist;
+  indices_dist.reserve( 128 );
+
+  RadiusResultSet<float, int> resultSet(radius, indices_dist);
+  const size_t nFound = _kdtree.findNeighbors(resultSet, point.data, _params);
+
+  if (_params.sorted)
+    std::sort(indices_dist.begin(), indices_dist.end(), IndexDist_Sorter() );
+
+  k_indices.resize(nFound);
+  k_sqr_distances.resize(nFound);
+  for(int i=0; i<nFound; i++ ){
+    k_indices[i]       = indices_dist[i].first;
+    k_sqr_distances[i] = indices_dist[i].second;
+  }
+  return nFound;
+}
+
+template<typename PointT> inline
+size_t KdTreeFLANN<PointT>::PointCloud_Adaptor::kdtree_get_point_count() const {
+  if( indices ) return indices->size();
+  if( pcl)  return pcl->points.size();
+  return 0;
+}
+
+template<typename PointT> inline
+float KdTreeFLANN<PointT>::PointCloud_Adaptor::kdtree_get_pt(const size_t idx, int dim) const{
+  const PointT& p = ( indices ) ? pcl->points[(*indices)[idx]] : pcl->points[idx];
+  if (dim==0) return p.x;
+  else if (dim==1) return p.y;
+  else if (dim==2) return p.z;
+  else return 0.0;
+}
+
+}
+
+
+#endif

+ 58 - 0
launch/dlo.launch

@@ -0,0 +1,58 @@
+<!--
+
+  Copyright (c) 2021, University of California, Los Angeles
+
+  Authors: Kenny J. Chen, Brett T. Lopez
+  Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+
+-->
+
+<launch>
+
+  <arg name="robot_namespace" default="robot"/>
+
+  <arg name="pointcloud_topic" default="rslidar_points"/>
+  <arg name="imu_topic" default="imu_data"/>
+
+  <!-- DLO Odometry Node -->
+  <node ns="$(arg robot_namespace)" name="dlo_odom" pkg="direct_lidar_odometry" type="dlo_odom_node" output="screen" clear_params="true">
+
+    <!-- Load parameters -->
+    <rosparam file="$(find direct_lidar_odometry)/cfg/dlo.yaml" command="load"/>
+    <rosparam file="$(find direct_lidar_odometry)/cfg/params.yaml" command="load"/>
+
+    <!-- Subscriptions -->
+    <remap from="~pointcloud" to="$(arg pointcloud_topic)"/>
+    <remap from="~imu" to="$(arg imu_topic)"/>
+
+    <!-- Publications -->
+    <remap from="~odom" to="dlo/odom_node/odom"/>
+    <remap from="~kfs" to="dlo/odom_node/odom/keyframe"/>
+    <remap from="~keyframe" to="dlo/odom_node/pointcloud/keyframe"/>
+
+  </node>
+
+  <!-- DLO Mapping Node -->
+  <node ns="$(arg robot_namespace)" name="dlo_map" pkg="direct_lidar_odometry" type="dlo_map_node" output="screen" clear_params="true">
+
+    <!-- Load parameters -->
+    <rosparam file="$(find direct_lidar_odometry)/cfg/dlo.yaml" command="load"/>
+
+    <!-- Subscriptions -->
+    <remap from="~keyframes" to="dlo/odom_node/pointcloud/keyframe"/>
+
+    <!-- Publications -->
+    <remap from="~map" to="dlo/map_node/map"/>
+
+  </node>
+
+
+
+  <!-- RViz -->
+  <node pkg="rviz" type="rviz" name="dlo_rviz" args="-d $(find direct_lidar_odometry)/launch/dlo.rviz"/>
+
+
+
+
+
+</launch>

File diff suppressed because it is too large
+ 264 - 0
launch/dlo.rviz


+ 28 - 0
package.xml

@@ -0,0 +1,28 @@
+<?xml version="1.0"?>
+
+<package format="2">
+
+  <name>direct_lidar_odometry</name>
+  <version>1.0.0</version>
+  <description>Direct LiDAR Odometry: Fast Localization with Dense Point Clouds</description>
+
+  <maintainer email="kennyjchen@ucla.edu">Kenny J. Chen</maintainer>
+  <maintainer email="btlopez@ucla.edu">Brett T. Lopez</maintainer>
+
+  <author>Kenny J. Chen</author>
+  <author>Brett T. Lopez</author>
+
+  <license>MIT</license>
+
+  <buildtool_depend>catkin</buildtool_depend>
+
+  <depend>roscpp</depend>
+  <depend>std_msgs</depend>
+  <depend>sensor_msgs</depend>
+  <depend>geometry_msgs</depend>
+  <depend>pcl_ros</depend>
+
+  <export>
+  </export>
+
+</package>

+ 134 - 0
src/dlo/map.cc

@@ -0,0 +1,134 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/map.h"
+
+std::atomic<bool> dlo::MapNode::abort_(false);
+
+
+/**
+ * Constructor
+ **/
+
+dlo::MapNode::MapNode(ros::NodeHandle node_handle) : nh(node_handle) {
+
+  this->getParams();
+
+  this->abort_timer = this->nh.createTimer(ros::Duration(0.01), &dlo::MapNode::abortTimerCB, this);
+  this->publish_timer = this->nh.createTimer(ros::Duration(this->publish_freq_), &dlo::MapNode::publishTimerCB, this);
+  
+  this->keyframe_sub = this->nh.subscribe("keyframes", 1, &dlo::MapNode::keyframeCB, this);
+  this->map_pub = this->nh.advertise<sensor_msgs::PointCloud2>("map", 1);
+
+  // initialize map
+  this->dlo_map = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+
+  ROS_INFO("DLO Map Node Initialized");
+
+}
+
+
+/**
+ * Destructor
+ **/
+
+dlo::MapNode::~MapNode() {}
+
+
+/**
+ * Get Params
+ *
+ *
+ *
+ **/
+
+void dlo::MapNode::getParams() {
+
+  ros::param::param<std::string>("~dlo/odomNode/odom_frame", this->odom_frame, "odom");
+  ros::param::param<double>("~dlo/mapNode/publishFreq", this->publish_freq_, 1.0);
+  ros::param::param<double>("~dlo/mapNode/leafSize", this->leaf_size_, 0.5);
+
+  // Get Node NS and Remove Leading Character
+  std::string ns = ros::this_node::getNamespace();
+  ns.erase(0,1);
+
+  // Concatenate Frame Name Strings
+  this->odom_frame = ns + "/" + this->odom_frame;
+
+}
+
+
+/**
+ * Start Map Node
+ **/
+
+void dlo::MapNode::start() {
+  ROS_INFO("Starting DLO Map Node");
+}
+
+
+/**
+ * Stop Map Node
+ **/
+
+void dlo::MapNode::stop() {
+  ROS_WARN("Stopping DLO Map Node");
+
+  // shutdown
+  ros::shutdown();
+}
+
+
+/**
+ * Abort Timer Callback
+ **/
+
+void dlo::MapNode::abortTimerCB(const ros::TimerEvent& e) {
+  if (abort_) {
+    stop();
+  }
+}
+
+
+/**
+ * Publish Timer Callback
+ **/
+
+void dlo::MapNode::publishTimerCB(const ros::TimerEvent& e) {
+
+  this->voxelgrid.setLeafSize(this->leaf_size_, this->leaf_size_, this->leaf_size_);
+  this->voxelgrid.setInputCloud(this->dlo_map);
+  this->voxelgrid.filter(*this->dlo_map);
+
+  if (this->dlo_map->points.size() == this->dlo_map->width * this->dlo_map->height) {
+    sensor_msgs::PointCloud2 map_ros;
+    pcl::toROSMsg(*this->dlo_map, map_ros);
+    map_ros.header.stamp = ros::Time::now();
+    map_ros.header.frame_id = this->odom_frame;
+    this->map_pub.publish(map_ros);
+  }
+  
+}
+
+
+/**
+ * Node Callback
+ **/
+
+void dlo::MapNode::keyframeCB(const sensor_msgs::PointCloud2ConstPtr& keyframe) {
+
+  // convert scan to pcl format
+  pcl::PointCloud<PointType>::Ptr keyframe_pcl = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  pcl::fromROSMsg(*keyframe, *keyframe_pcl);
+
+  // save keyframe to map
+  this->map_stamp = keyframe->header.stamp;
+  *this->dlo_map += *keyframe_pcl;
+
+}

+ 34 - 0
src/dlo/map_node.cc

@@ -0,0 +1,34 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/map.h"
+
+void controlC(int sig) {
+
+  dlo::MapNode::abort();
+
+}
+
+int main(int argc, char** argv) {
+
+  ros::init(argc, argv, "dlo_map_node");
+  ros::NodeHandle nh("~");
+
+  signal(SIGTERM, controlC);
+  sleep(0.5);
+
+  dlo::MapNode node(nh);
+  ros::AsyncSpinner spinner(1);
+  spinner.start();
+  node.start();
+  ros::waitForShutdown();
+
+  return 0;
+
+}

+ 1410 - 0
src/dlo/odom.cc

@@ -0,0 +1,1410 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/odom.h"
+
+std::atomic<bool> dlo::OdomNode::abort_(false);
+
+
+/**
+ * Constructor
+ **/
+
+dlo::OdomNode::OdomNode(ros::NodeHandle node_handle) : nh(node_handle) {
+
+  this->getParams();
+
+  this->stop_publish_thread = false;
+  this->stop_publish_keyframe_thread = false;
+  this->stop_metrics_thread = false;
+  this->stop_debug_thread = false;
+
+  this->dlo_initialized = false;
+  this->imu_calibrated = false;
+  this->normals_initialized = false;
+
+  this->icp_sub = this->nh.subscribe("pointcloud", 1, &dlo::OdomNode::icpCB, this);
+  this->imu_sub = this->nh.subscribe("imu", 1, &dlo::OdomNode::imuCB, this);
+
+  this->odom_pub = this->nh.advertise<nav_msgs::Odometry>("odom", 1);
+  this->kf_pub = this->nh.advertise<nav_msgs::Odometry>("kfs", 1, true);
+  this->keyframe_pub = this->nh.advertise<sensor_msgs::PointCloud2>("keyframe", 1, true);
+
+  this->odom.pose.pose.position.x = 0.;
+  this->odom.pose.pose.position.y = 0.;
+  this->odom.pose.pose.position.z = 0.;
+  this->odom.pose.pose.orientation.w = 1.;
+  this->odom.pose.pose.orientation.x = 0.;
+  this->odom.pose.pose.orientation.y = 0.;
+  this->odom.pose.pose.orientation.z = 0.;
+  this->odom.pose.covariance = {0.};
+
+  this->T = Eigen::Matrix4f::Identity();
+  this->T_s2s = Eigen::Matrix4f::Identity();
+  this->T_s2s_prev = Eigen::Matrix4f::Identity();
+
+  this->pose_s2s = Eigen::Vector3f(0., 0., 0.);
+  this->rotq_s2s = Eigen::Quaternionf(1., 0., 0., 0.);
+
+  this->pose = Eigen::Vector3f(0., 0., 0.);
+  this->rotq = Eigen::Quaternionf(1., 0., 0., 0.);
+
+  this->imu_SE3 = Eigen::Matrix4f::Identity();
+
+  this->imu_bias.gyro.x = 0.;
+  this->imu_bias.gyro.y = 0.;
+  this->imu_bias.gyro.z = 0.;
+  this->imu_bias.accel.x = 0.;
+  this->imu_bias.accel.y = 0.;
+  this->imu_bias.accel.z = 0.;
+
+  this->imu_meas.stamp = 0.;
+  this->imu_meas.ang_vel.x = 0.;
+  this->imu_meas.ang_vel.y = 0.;
+  this->imu_meas.ang_vel.z = 0.;
+  this->imu_meas.lin_accel.x = 0.;
+  this->imu_meas.lin_accel.y = 0.;
+  this->imu_meas.lin_accel.z = 0.;
+
+  this->imu_buffer.set_capacity(this->imu_buffer_size_);
+  this->first_imu_time = 0.;
+
+  this->original_scan = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->current_scan = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->current_scan_t = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+
+  this->keyframe_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->keyframes_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->num_keyframes = 0;
+
+  this->submap_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->submap_hasChanged = true;
+  this->submap_kf_idx_prev.clear();
+
+  this->source_cloud = nullptr;
+  this->target_cloud = nullptr;
+
+  this->convex_hull.setDimension(3);
+  this->concave_hull.setDimension(3);
+  this->concave_hull.setAlpha(this->keyframe_thresh_dist_);
+  this->concave_hull.setKeepInformation(true);
+
+  this->gicp_s2s.setCorrespondenceRandomness(this->gicps2s_k_correspondences_);
+  this->gicp_s2s.setMaxCorrespondenceDistance(this->gicps2s_max_corr_dist_);
+  this->gicp_s2s.setMaximumIterations(this->gicps2s_max_iter_);
+  this->gicp_s2s.setTransformationEpsilon(this->gicps2s_transformation_ep_);
+  this->gicp_s2s.setEuclideanFitnessEpsilon(this->gicps2s_euclidean_fitness_ep_);
+  this->gicp_s2s.setRANSACIterations(this->gicps2s_ransac_iter_);
+  this->gicp_s2s.setRANSACOutlierRejectionThreshold(this->gicps2s_ransac_inlier_thresh_);
+
+  this->gicp.setCorrespondenceRandomness(this->gicps2m_k_correspondences_);
+  this->gicp.setMaxCorrespondenceDistance(this->gicps2m_max_corr_dist_);
+  this->gicp.setMaximumIterations(this->gicps2m_max_iter_);
+  this->gicp.setTransformationEpsilon(this->gicps2m_transformation_ep_);
+  this->gicp.setEuclideanFitnessEpsilon(this->gicps2m_euclidean_fitness_ep_);
+  this->gicp.setRANSACIterations(this->gicps2m_ransac_iter_);
+  this->gicp.setRANSACOutlierRejectionThreshold(this->gicps2m_ransac_inlier_thresh_);
+
+  pcl::Registration<PointType, PointType>::KdTreeReciprocalPtr temp;
+  this->gicp_s2s.setSearchMethodSource(temp, true);
+  this->gicp_s2s.setSearchMethodTarget(temp, true);
+  this->gicp.setSearchMethodSource(temp, true);
+  this->gicp.setSearchMethodTarget(temp, true);
+
+  this->crop.setNegative(true);
+  this->crop.setMin(Eigen::Vector4f(-this->crop_size_, -this->crop_size_, -this->crop_size_, 1.0));
+  this->crop.setMax(Eigen::Vector4f(this->crop_size_, this->crop_size_, this->crop_size_, 1.0));
+
+  this->vf_scan.setLeafSize(this->vf_scan_res_, this->vf_scan_res_, this->vf_scan_res_);
+  this->vf_submap.setLeafSize(this->vf_submap_res_, this->vf_submap_res_, this->vf_submap_res_);
+
+  this->metrics.spaciousness.push_back(0.);
+
+  // CPU Specs
+  char CPUBrandString[0x40];
+  unsigned int CPUInfo[4] = {0,0,0,0};
+  __cpuid(0x80000000, CPUInfo[0], CPUInfo[1], CPUInfo[2], CPUInfo[3]);
+  unsigned int nExIds = CPUInfo[0];
+  memset(CPUBrandString, 0, sizeof(CPUBrandString));
+  for (unsigned int i = 0x80000000; i <= nExIds; ++i) {
+    __cpuid(i, CPUInfo[0], CPUInfo[1], CPUInfo[2], CPUInfo[3]);
+    if (i == 0x80000002)
+      memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
+    else if (i == 0x80000003)
+      memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
+    else if (i == 0x80000004)
+      memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
+  }
+
+  this->cpu_type = CPUBrandString;
+  boost::trim(this->cpu_type);
+
+  FILE* file;
+  struct tms timeSample;
+  char line[128];
+
+  this->lastCPU = times(&timeSample);
+  this->lastSysCPU = timeSample.tms_stime;
+  this->lastUserCPU = timeSample.tms_utime;
+
+  file = fopen("/proc/cpuinfo", "r");
+  this->numProcessors = 0;
+  while(fgets(line, 128, file) != NULL) {
+      if (strncmp(line, "processor", 9) == 0) this->numProcessors++;
+  }
+  fclose(file);
+
+  ROS_INFO("DLO Odom Node Initialized");
+
+}
+
+
+/**
+ * Destructor
+ **/
+
+dlo::OdomNode::~OdomNode() {}
+
+
+
+/**
+ * Odom Node Parameters
+ **/
+
+void dlo::OdomNode::getParams() {
+    std::vector<double> extRotV;
+    std::vector<double> extRPYV;
+    std::vector<double> extTransV;
+
+    ros::param::param<std::vector<double>>("/robot/dlo_odom/dlo/odomNode/extrinsicRot", extRotV, std::vector<double>());
+    ros::param::param<std::vector<double>>("/robot/dlo_odom/dlo/odomNode/extrinsicRPY", extRPYV, std::vector<double>());
+    ros::param::param<std::vector<double>>("/robot/dlo_odom/dlo/odomNode/extrinsicTrans", extTransV, std::vector<double>());
+    extRot = Eigen::Map<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>(extRotV.data(), 3, 3);
+    extRPY = Eigen::Map<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>(extRPYV.data(), 3, 3);
+  // Version
+  ros::param::param<std::string>("~dlo/version", this->version_, "0.0.0");
+
+  // Frames
+  ros::param::param<std::string>("~dlo/odomNode/odom_frame", this->odom_frame, "odom");
+  ros::param::param<std::string>("~dlo/odomNode/child_frame", this->child_frame, "base_link");
+
+  // Get Node NS and Remove Leading Character
+  std::string ns = ros::this_node::getNamespace();
+  ns.erase(0,1);
+
+  // Concatenate Frame Name Strings
+  this->odom_frame = ns + "/" + this->odom_frame;
+  this->child_frame = ns + "/" + this->child_frame;
+
+  // Gravity alignment
+  ros::param::param<bool>("~dlo/gravityAlign", this->gravity_align_, false);
+
+  // Keyframe Threshold
+  ros::param::param<double>("~dlo/odomNode/keyframe/threshD", this->keyframe_thresh_dist_, 0.1);
+  ros::param::param<double>("~dlo/odomNode/keyframe/threshR", this->keyframe_thresh_rot_, 1.0);
+
+  // Submap
+  ros::param::param<int>("~dlo/odomNode/submap/keyframe/knn", this->submap_knn_, 10);
+  ros::param::param<int>("~dlo/odomNode/submap/keyframe/kcv", this->submap_kcv_, 10);
+  ros::param::param<int>("~dlo/odomNode/submap/keyframe/kcc", this->submap_kcc_, 10);
+
+  // Crop Box Filter
+  ros::param::param<bool>("~dlo/odomNode/preprocessing/cropBoxFilter/use", this->crop_use_, false);
+  ros::param::param<double>("~dlo/odomNode/preprocessing/cropBoxFilter/size", this->crop_size_, 1.0);
+
+  // Voxel Grid Filter
+  ros::param::param<bool>("~dlo/odomNode/preprocessing/voxelFilter/scan/use", this->vf_scan_use_, true);
+  ros::param::param<double>("~dlo/odomNode/preprocessing/voxelFilter/scan/res", this->vf_scan_res_, 0.05);
+  ros::param::param<bool>("~dlo/odomNode/preprocessing/voxelFilter/submap/use", this->vf_submap_use_, false);
+  ros::param::param<double>("~dlo/odomNode/preprocessing/voxelFilter/submap/res", this->vf_submap_res_, 0.1);
+
+  // Adaptive Parameters
+  ros::param::param<bool>("~dlo/adaptiveParams", this->adaptive_params_use_, false);
+
+  // IMU
+  ros::param::param<bool>("~dlo/imu", this->imu_use_, false);
+  ros::param::param<int>("~dlo/odomNode/imu/calibTime", this->imu_calib_time_, 3);
+  ros::param::param<int>("~dlo/odomNode/imu/bufferSize", this->imu_buffer_size_, 2000);
+
+  // GICP
+  ros::param::param<int>("~dlo/odomNode/gicp/minNumPoints", this->gicp_min_num_points_, 100);
+  ros::param::param<int>("~dlo/odomNode/gicp/s2s/kCorrespondences", this->gicps2s_k_correspondences_, 20);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2s/maxCorrespondenceDistance", this->gicps2s_max_corr_dist_, std::sqrt(std::numeric_limits<double>::max()));
+  ros::param::param<int>("~dlo/odomNode/gicp/s2s/maxIterations", this->gicps2s_max_iter_, 64);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2s/transformationEpsilon", this->gicps2s_transformation_ep_, 0.0005);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2s/euclideanFitnessEpsilon", this->gicps2s_euclidean_fitness_ep_, -std::numeric_limits<double>::max());
+  ros::param::param<int>("~dlo/odomNode/gicp/s2s/ransac/iterations", this->gicps2s_ransac_iter_, 0);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2s/ransac/outlierRejectionThresh", this->gicps2s_ransac_inlier_thresh_, 0.05);
+  ros::param::param<int>("~dlo/odomNode/gicp/s2m/kCorrespondences", this->gicps2m_k_correspondences_, 20);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2m/maxCorrespondenceDistance", this->gicps2m_max_corr_dist_, std::sqrt(std::numeric_limits<double>::max()));
+  ros::param::param<int>("~dlo/odomNode/gicp/s2m/maxIterations", this->gicps2m_max_iter_, 64);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2m/transformationEpsilon", this->gicps2m_transformation_ep_, 0.0005);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2m/euclideanFitnessEpsilon", this->gicps2m_euclidean_fitness_ep_, -std::numeric_limits<double>::max());
+  ros::param::param<int>("~dlo/odomNode/gicp/s2m/ransac/iterations", this->gicps2m_ransac_iter_, 0);
+  ros::param::param<double>("~dlo/odomNode/gicp/s2m/ransac/outlierRejectionThresh", this->gicps2m_ransac_inlier_thresh_, 0.05);
+
+}
+
+
+/**
+ * Start Odom Thread
+ **/
+
+void dlo::OdomNode::start() {
+  ROS_INFO("Starting DLO Odometry Node");
+
+  printf("\033[2J\033[1;1H");
+  std::cout << std::endl << "==== Direct LiDAR Odometry v" << this->version_ << " ====" << std::endl << std::endl;
+
+}
+
+
+/**
+ * Stop Odom Thread
+ **/
+
+void dlo::OdomNode::stop() {
+  ROS_WARN("Stopping DLO Odometry Node");
+
+  this->stop_publish_thread = true;
+  if (this->publish_thread.joinable()) {
+    this->publish_thread.join();
+  }
+
+  this->stop_publish_keyframe_thread = true;
+  if (this->publish_keyframe_thread.joinable()) {
+    this->publish_keyframe_thread.join();
+  }
+
+  this->stop_metrics_thread = true;
+  if (this->metrics_thread.joinable()) {
+    this->metrics_thread.join();
+  }
+
+  this->stop_debug_thread = true;
+  if (this->debug_thread.joinable()) {
+    this->debug_thread.join();
+  }
+
+  ros::shutdown();
+}
+
+
+/**
+ * Abort Timer Callback
+ **/
+
+void dlo::OdomNode::abortTimerCB(const ros::TimerEvent& e) {
+  if (abort_) {
+    stop();
+  }
+}
+
+
+/**
+ * Publish to ROS
+ **/
+
+void dlo::OdomNode::publishToROS() {
+  this->publishPose();
+  this->publishTransform();
+}
+
+
+/**
+ * Publish Pose
+ **/
+
+void dlo::OdomNode::publishPose() {
+
+  // Sign flip check
+  static Eigen::Quaternionf q_diff{1., 0., 0., 0.};
+  static Eigen::Quaternionf q_last{1., 0., 0., 0.};
+
+  q_diff = q_last.conjugate()*this->rotq;
+
+  // If q_diff has negative real part then there was a sign flip
+  if (q_diff.w() < 0) {
+    this->rotq.w() = -this->rotq.w();
+    this->rotq.vec() = -this->rotq.vec();
+  }
+
+  q_last = this->rotq;
+
+  this->odom.pose.pose.position.x = this->pose[0];
+  this->odom.pose.pose.position.y = this->pose[1];
+  this->odom.pose.pose.position.z = this->pose[2];
+
+  this->odom.pose.pose.orientation.w = this->rotq.w();
+  this->odom.pose.pose.orientation.x = this->rotq.x();
+  this->odom.pose.pose.orientation.y = this->rotq.y();
+  this->odom.pose.pose.orientation.z = this->rotq.z();
+
+  this->odom.header.stamp = this->scan_stamp;
+  this->odom.header.frame_id = this->odom_frame;
+  this->odom.child_frame_id = this->child_frame;
+  this->odom_pub.publish(this->odom);
+
+}
+
+
+/**
+ * Publish Transform
+ **/
+
+void dlo::OdomNode::publishTransform() {
+
+  static tf2_ros::TransformBroadcaster br;
+  geometry_msgs::TransformStamped transformStamped;
+
+  transformStamped.header.stamp = this->scan_stamp;
+  transformStamped.header.frame_id = this->odom_frame;
+//  transformStamped.child_frame_id = this->child_frame;
+  transformStamped.child_frame_id = "rslidar";
+
+  transformStamped.transform.translation.x = this->pose[0];
+  transformStamped.transform.translation.y = this->pose[1];
+  transformStamped.transform.translation.z = this->pose[2];
+
+  transformStamped.transform.rotation.w = this->rotq.w();
+  transformStamped.transform.rotation.x = this->rotq.x();
+  transformStamped.transform.rotation.y = this->rotq.y();
+  transformStamped.transform.rotation.z = this->rotq.z();
+
+  br.sendTransform(transformStamped);
+
+}
+
+
+/**
+ * Publish Keyframe Pose and Scan
+ **/
+
+void dlo::OdomNode::publishKeyframe() {
+
+  // Publish keyframe pose
+  this->kf.header.stamp = this->scan_stamp;
+  this->kf.header.frame_id = this->odom_frame;
+  this->kf.child_frame_id = this->child_frame;
+
+  this->kf.pose.pose.position.x = this->pose[0];
+  this->kf.pose.pose.position.y = this->pose[1];
+  this->kf.pose.pose.position.z = this->pose[2];
+
+  this->kf.pose.pose.orientation.w = this->rotq.w();
+  this->kf.pose.pose.orientation.x = this->rotq.x();
+  this->kf.pose.pose.orientation.y = this->rotq.y();
+  this->kf.pose.pose.orientation.z = this->rotq.z();
+
+  this->kf_pub.publish(this->kf);
+
+  // Publish keyframe scan
+  if (this->keyframe_cloud->points.size() == this->keyframe_cloud->width * this->keyframe_cloud->height) {
+    sensor_msgs::PointCloud2 keyframe_cloud_ros;
+    pcl::toROSMsg(*this->keyframe_cloud, keyframe_cloud_ros);
+    keyframe_cloud_ros.header.stamp = this->scan_stamp;
+    keyframe_cloud_ros.header.frame_id = this->odom_frame;
+    this->keyframe_pub.publish(keyframe_cloud_ros);
+  }
+
+}
+
+
+/**
+ * Preprocessing
+ **/
+
+void dlo::OdomNode::preprocessPoints() {
+
+  // Original Scan
+  *this->original_scan = *this->current_scan;
+
+  // Remove NaNs
+  std::vector<int> idx;
+  this->current_scan->is_dense = false;
+  pcl::removeNaNFromPointCloud(*this->current_scan, *this->current_scan, idx);
+
+  // Crop Box Filter
+  if (this->crop_use_) {
+    this->crop.setInputCloud(this->current_scan);
+    this->crop.filter(*this->current_scan);
+  }
+
+  // Voxel Grid Filter
+  if (this->vf_scan_use_) {
+    this->vf_scan.setInputCloud(this->current_scan);
+    this->vf_scan.filter(*this->current_scan);
+  }
+
+}
+
+
+/**
+ * Initialize Input Target
+ **/
+
+void dlo::OdomNode::initializeInputTarget() {
+
+  this->prev_frame_stamp = this->curr_frame_stamp;
+
+  // Convert ros message
+  this->target_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->target_cloud = this->current_scan;
+  this->gicp_s2s.setInputTarget(this->target_cloud);
+
+  // initialize keyframes
+  pcl::PointCloud<PointType>::Ptr first_keyframe (new pcl::PointCloud<PointType>);
+  pcl::transformPointCloud (*this->target_cloud, *first_keyframe, this->T);
+
+  // voxelization for submap
+  if (this->vf_submap_use_) {
+    this->vf_submap.setInputCloud(first_keyframe);
+    this->vf_submap.filter(*first_keyframe);
+  }
+
+  // keep history of keyframes
+  this->keyframes.push_back(std::make_pair(std::make_pair(this->pose, this->rotq), first_keyframe));
+
+  *this->keyframes_cloud += *first_keyframe;
+  *this->keyframe_cloud = *first_keyframe;
+
+  this->publish_keyframe_thread = std::thread( &dlo::OdomNode::publishKeyframe, this );
+  this->publish_keyframe_thread.detach();
+
+  ++this->num_keyframes;
+
+}
+
+
+/**
+ * Set Input Sources
+ **/
+
+void dlo::OdomNode::setInputSources(){
+
+  // set the input source for the S2S gicp
+  // this builds the KdTree of the source cloud
+  // this does not build the KdTree for s2m because force_no_update is true
+  this->gicp_s2s.setInputSource(this->current_scan);
+
+  // set pcl::Registration input source for S2M gicp using custom NanoGICP function
+  this->gicp.registerInputSource(this->current_scan);
+
+  // now set the KdTree of S2M gicp using previously built KdTree
+  this->gicp.source_kdtree_ = this->gicp_s2s.source_kdtree_;
+  this->gicp.source_covs_.clear();
+
+}
+
+
+/**
+ * Gravity Alignment
+ **/
+
+void dlo::OdomNode::gravityAlign() {
+
+  // get average acceleration vector for 1 second and normalize
+  Eigen::Vector3f lin_accel = Eigen::Vector3f::Zero();
+  const double then = ros::Time::now().toSec();
+  int n=0;
+  while ((ros::Time::now().toSec() - then) < 1.) {
+    lin_accel[0] += this->imu_meas.lin_accel.x;
+    lin_accel[1] += this->imu_meas.lin_accel.y;
+    lin_accel[2] += this->imu_meas.lin_accel.z;
+    ++n;
+  }
+  lin_accel[0] /= n; lin_accel[1] /= n; lin_accel[2] /= n;
+
+  // normalize
+  double lin_norm = sqrt(pow(lin_accel[0], 2) + pow(lin_accel[1], 2) + pow(lin_accel[2], 2));
+  lin_accel[0] /= lin_norm; lin_accel[1] /= lin_norm; lin_accel[2] /= lin_norm;
+
+  // define gravity vector (assume point downwards)
+  Eigen::Vector3f grav;
+  grav << 0, 0, 1;
+
+  // calculate angle between the two vectors
+  Eigen::Quaternionf grav_q = Eigen::Quaternionf::FromTwoVectors(lin_accel, grav);
+
+  // normalize
+  double grav_norm = sqrt(grav_q.w()*grav_q.w() + grav_q.x()*grav_q.x() + grav_q.y()*grav_q.y() + grav_q.z()*grav_q.z());
+  grav_q.w() /= grav_norm; grav_q.x() /= grav_norm; grav_q.y() /= grav_norm; grav_q.z() /= grav_norm;
+
+  // set gravity aligned orientation
+  this->rotq = grav_q;
+  this->T.block(0,0,3,3) = this->rotq.toRotationMatrix();
+  this->T_s2s.block(0,0,3,3) = this->rotq.toRotationMatrix();
+  this->T_s2s_prev.block(0,0,3,3) = this->rotq.toRotationMatrix();
+
+  // rpy
+  auto euler = grav_q.toRotationMatrix().eulerAngles(2, 1, 0);
+  double yaw = euler[0] * (180.0/M_PI);
+  double pitch = euler[1] * (180.0/M_PI);
+  double roll = euler[2] * (180.0/M_PI);
+
+  std::cout << "done" << std::endl;
+  std::cout << "  Roll [deg]: " << roll << std::endl;
+  std::cout << "  Pitch [deg]: " << pitch << std::endl << std::endl;
+}
+
+
+/**
+ * Initialize 6DOF
+ **/
+
+void dlo::OdomNode::initializeDLO() {
+
+  // Calibrate IMU
+  if (!this->imu_calibrated && this->imu_use_) {
+    return;
+  }
+
+  // Gravity Align
+  if (this->gravity_align_ && this->imu_use_ && this->imu_calibrated) {
+    std::cout << "Aligning to gravity... "; std::cout.flush();
+    this->gravityAlign();
+  }
+
+  this->dlo_initialized = true;
+  std::cout << "DLO initialized! Starting localization..." << std::endl;
+
+}
+
+
+/**
+ * ICP Point Cloud Callback
+ **/
+
+void dlo::OdomNode::icpCB(const sensor_msgs::PointCloud2ConstPtr& pc) {
+
+  double then = ros::Time::now().toSec();
+  this->scan_stamp = pc->header.stamp;
+  this->curr_frame_stamp = pc->header.stamp.toSec();
+
+  // If there are too few points in the pointcloud, try again
+  this->current_scan = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  pcl::fromROSMsg(*pc, *this->current_scan);
+  if (this->current_scan->points.size() < this->gicp_min_num_points_) {
+    ROS_WARN("Low number of points!");
+    return;
+  }
+
+  // DLO Initialization procedures (IMU calib, gravity align)
+  if (!this->dlo_initialized) {
+    this->initializeDLO();
+    return;
+  }
+
+  // Preprocess points
+  this->preprocessPoints();
+
+  // Compute Metrics
+  this->metrics_thread = std::thread( &dlo::OdomNode::computeMetrics, this );
+  this->metrics_thread.detach();
+
+  // Set Adaptive Parameters
+  if (this->adaptive_params_use_){
+    this->setAdaptiveParams();
+  }
+
+  // Set initial frame as target
+  if(this->target_cloud == nullptr) {
+    this->initializeInputTarget();
+    return;
+  }
+
+  // Set source frame
+  this->source_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->source_cloud = this->current_scan;
+
+  // Set new frame as input source for both gicp objects
+  this->setInputSources();
+
+  // Get the next pose via IMU + S2S + S2M
+  this->getNextPose();
+
+  // Update current keyframe poses and map
+  this->updateKeyframes();
+
+  // Update trajectory
+  this->trajectory.push_back( std::make_pair(this->pose, this->rotq) );
+
+  // Update next time stamp
+  this->prev_frame_stamp = this->curr_frame_stamp;
+
+  // Update some statistics
+  this->comp_times.push_back(ros::Time::now().toSec() - then);
+
+  // Publish stuff to ROS
+  this->publish_thread = std::thread( &dlo::OdomNode::publishToROS, this );
+  this->publish_thread.detach();
+
+  // Debug statements and publish custom DLO message
+  this->debug_thread = std::thread( &dlo::OdomNode::debug, this );
+  this->debug_thread.detach();
+
+}
+
+
+/**
+ * IMU Callback
+ **/
+
+void dlo::OdomNode::imuCB(const sensor_msgs::Imu::ConstPtr& imu) {
+
+  if (!this->imu_use_) {
+    return;
+  }
+
+
+    auto imuC = imuConverter(*imu);
+  double ang_vel[3], lin_accel[3];
+
+  // Get IMU samples
+  ang_vel[0] = imuC.angular_velocity.x;
+  ang_vel[1] = imuC.angular_velocity.y;
+  ang_vel[2] = imuC.angular_velocity.z;
+
+  lin_accel[0] = imuC.linear_acceleration.x;
+  lin_accel[1] = imuC.linear_acceleration.y;
+  lin_accel[2] = imuC.linear_acceleration.z;
+
+  if (this->first_imu_time == 0.) {
+    this->first_imu_time = imu->header.stamp.toSec();
+  }
+
+  // IMU calibration procedure - do for three seconds
+  if (!this->imu_calibrated) {
+
+    static int num_samples = 0;
+    static bool print = true;
+
+    if ((imu->header.stamp.toSec() - this->first_imu_time) < this->imu_calib_time_) {
+
+      num_samples++;
+
+      this->imu_bias.gyro.x += ang_vel[0];
+      this->imu_bias.gyro.y += ang_vel[1];
+      this->imu_bias.gyro.z += ang_vel[2];
+
+      this->imu_bias.accel.x += lin_accel[0];
+      this->imu_bias.accel.y += lin_accel[1];
+      this->imu_bias.accel.z += lin_accel[2];
+
+      if(print) {
+        std::cout << "Calibrating IMU for " << this->imu_calib_time_ << " seconds... "; std::cout.flush();
+        print = false;
+      }
+
+    } else {
+
+      this->imu_bias.gyro.x /= num_samples;
+      this->imu_bias.gyro.y /= num_samples;
+      this->imu_bias.gyro.z /= num_samples;
+
+      this->imu_bias.accel.x /= num_samples;
+      this->imu_bias.accel.y /= num_samples;
+      this->imu_bias.accel.z /= num_samples;
+
+      this->imu_calibrated = true;
+
+      std::cout << "done" << std::endl;
+      std::cout << "  Gyro biases [xyz]: " << this->imu_bias.gyro.x << ", " << this->imu_bias.gyro.y << ", " << this->imu_bias.gyro.z << std::endl << std::endl;
+
+    }
+
+  } else {
+
+    // Apply the calibrated bias to the new IMU measurements
+    this->imu_meas.stamp = imu->header.stamp.toSec();
+
+    this->imu_meas.ang_vel.x = ang_vel[0] - this->imu_bias.gyro.x;
+    this->imu_meas.ang_vel.y = ang_vel[1] - this->imu_bias.gyro.y;
+    this->imu_meas.ang_vel.z = ang_vel[2] - this->imu_bias.gyro.z;
+
+    this->imu_meas.lin_accel.x = lin_accel[0];
+    this->imu_meas.lin_accel.y = lin_accel[1];
+    this->imu_meas.lin_accel.z = lin_accel[2];
+
+    // Store into circular buffer
+    this->mtx_imu.lock();
+    this->imu_buffer.push_front(this->imu_meas);
+    this->mtx_imu.unlock();
+
+  }
+
+}
+
+
+/**
+ * Get Next Pose
+ **/
+
+void dlo::OdomNode::getNextPose() {
+
+  //
+  // FRAME-TO-FRAME PROCEDURE
+  //
+
+  // Align using IMU prior if available
+  pcl::PointCloud<PointType>::Ptr aligned (new pcl::PointCloud<PointType>);
+
+  if (this->imu_use_) {
+    this->integrateIMU();
+    this->gicp_s2s.align(*aligned, this->imu_SE3);
+  } else {
+    this->gicp_s2s.align(*aligned);
+  }
+
+  // if first iteration, store target covariance into keyframe normals
+  if (!this->normals_initialized) {
+    this->keyframe_normals.push_back(this->gicp_s2s.getTargetCovariances());
+    this->normals_initialized = true;
+  }
+
+  // Get the local S2S transform
+  Eigen::Matrix4f T_S2S = this->gicp_s2s.getFinalTransformation();
+
+  // Get the global S2S transform
+  this->propagateS2S(T_S2S);
+
+  // reuse covariances from s2s for s2m
+  this->gicp.source_covs_ = this->gicp_s2s.source_covs_;
+
+  // Swap source and target (which also swaps KdTrees internally) for next S2S
+  this->gicp_s2s.swapSourceAndTarget();
+
+  //
+  // FRAME-TO-SUBMAP
+  //
+
+  // Get current global submap
+  this->getSubmapKeyframes();
+
+  if (this->submap_hasChanged) {
+
+    // Set the current global submap as the target cloud
+    this->gicp.setInputTarget(this->submap_cloud);
+
+    // Set target cloud's normals as submap normals
+    this->gicp.setTargetCovariances( this->submap_normals );
+  }
+
+  // Align with current submap with global S2S transformation as initial guess
+  this->gicp.align(*aligned, this->T_s2s);
+
+  // Get final transformation in global frame
+  this->T = this->gicp.getFinalTransformation();
+
+  // Update the S2S transform for next propagation
+  this->T_s2s_prev = this->T;
+
+  // Update next global pose
+  // Both source and target clouds are in the global frame now, so tranformation is global
+  this->propagateS2M();
+
+  // Set next target cloud as current source cloud
+  *this->target_cloud = *this->source_cloud;
+
+}
+
+
+/**
+ * Integrate IMU
+ **/
+
+void dlo::OdomNode::integrateIMU() {
+
+  // Extract IMU data between the two frames
+  std::vector<ImuMeas> imu_frame;
+
+  for (const auto& i : this->imu_buffer) {
+
+    // IMU data between two frames is when:
+    //   current frame's timestamp minus imu timestamp is positive
+    //   previous frame's timestamp minus imu timestamp is negative
+    double curr_frame_imu_dt = this->curr_frame_stamp - i.stamp;
+    double prev_frame_imu_dt = this->prev_frame_stamp - i.stamp;
+
+    if (curr_frame_imu_dt >= 0. && prev_frame_imu_dt <= 0.) {
+
+      imu_frame.push_back(i);
+
+    }
+
+  }
+
+  // Sort measurements by time
+  std::sort(imu_frame.begin(), imu_frame.end(), this->comparatorImu);
+
+  // Relative IMU integration of gyro and accelerometer
+  double curr_imu_stamp = 0.;
+  double prev_imu_stamp = 0.;
+  double dt;
+
+  Eigen::Quaternionf q = Eigen::Quaternionf::Identity();
+
+  for (uint32_t i = 0; i < imu_frame.size(); ++i) {
+
+    if (prev_imu_stamp == 0.) {
+      prev_imu_stamp = imu_frame[i].stamp;
+      continue;
+    }
+
+    // Calculate difference in imu measurement times IN SECONDS
+    curr_imu_stamp = imu_frame[i].stamp;
+    dt = curr_imu_stamp - prev_imu_stamp;
+    prev_imu_stamp = curr_imu_stamp;
+    
+    // Relative gyro propagation quaternion dynamics
+    Eigen::Quaternionf qq = q;
+    q.w() -= 0.5*( qq.x()*imu_frame[i].ang_vel.x + qq.y()*imu_frame[i].ang_vel.y + qq.z()*imu_frame[i].ang_vel.z ) * dt;
+    q.x() += 0.5*( qq.w()*imu_frame[i].ang_vel.x - qq.z()*imu_frame[i].ang_vel.y + qq.y()*imu_frame[i].ang_vel.z ) * dt;
+    q.y() += 0.5*( qq.z()*imu_frame[i].ang_vel.x + qq.w()*imu_frame[i].ang_vel.y - qq.x()*imu_frame[i].ang_vel.z ) * dt;
+    q.z() += 0.5*( qq.x()*imu_frame[i].ang_vel.y - qq.y()*imu_frame[i].ang_vel.x + qq.w()*imu_frame[i].ang_vel.z ) * dt;
+
+  }
+
+  // Normalize quaternion
+  double norm = sqrt(q.w()*q.w() + q.x()*q.x() + q.y()*q.y() + q.z()*q.z());
+  q.w() /= norm; q.x() /= norm; q.y() /= norm; q.z() /= norm;
+
+  // Store IMU guess
+  this->imu_SE3 = Eigen::Matrix4f::Identity();
+  this->imu_SE3.block(0, 0, 3, 3) = q.toRotationMatrix();
+
+}
+
+
+/**
+ * Propagate S2S Alignment
+ **/
+
+void dlo::OdomNode::propagateS2S(Eigen::Matrix4f T) {
+
+  this->T_s2s = this->T_s2s_prev * T;
+  this->T_s2s_prev = this->T_s2s;
+
+  this->pose_s2s   << this->T_s2s(0,3), this->T_s2s(1,3), this->T_s2s(2,3);
+  this->rotSO3_s2s << this->T_s2s(0,0), this->T_s2s(0,1), this->T_s2s(0,2),
+                      this->T_s2s(1,0), this->T_s2s(1,1), this->T_s2s(1,2),
+                      this->T_s2s(2,0), this->T_s2s(2,1), this->T_s2s(2,2);
+
+  Eigen::Quaternionf q(this->rotSO3_s2s);
+
+  // Normalize quaternion
+  double norm = sqrt(q.w()*q.w() + q.x()*q.x() + q.y()*q.y() + q.z()*q.z());
+  q.w() /= norm; q.x() /= norm; q.y() /= norm; q.z() /= norm;
+  this->rotq_s2s = q;
+
+}
+
+
+/**
+ * Propagate S2M Alignment
+ **/
+
+void dlo::OdomNode::propagateS2M() {
+
+  this->pose   << this->T(0,3), this->T(1,3), this->T(2,3);
+  this->rotSO3 << this->T(0,0), this->T(0,1), this->T(0,2),
+                  this->T(1,0), this->T(1,1), this->T(1,2),
+                  this->T(2,0), this->T(2,1), this->T(2,2);
+
+  Eigen::Quaternionf q(this->rotSO3);
+
+  // Normalize quaternion
+  double norm = sqrt(q.w()*q.w() + q.x()*q.x() + q.y()*q.y() + q.z()*q.z());
+  q.w() /= norm; q.x() /= norm; q.y() /= norm; q.z() /= norm;
+  this->rotq = q;
+
+}
+
+
+/**
+ * Transform Current Scan
+ **/
+
+void dlo::OdomNode::transformCurrentScan() {
+  this->current_scan_t = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  pcl::transformPointCloud (*this->current_scan, *this->current_scan_t, this->T);
+}
+
+
+/**
+ * Compute Metrics
+ **/
+
+void dlo::OdomNode::computeMetrics() {
+  this->computeSpaciousness();
+}
+
+
+/**
+ * Compute Spaciousness of Current Scan
+ **/
+
+void dlo::OdomNode::computeSpaciousness() {
+
+  // compute range of points
+  std::vector<float> ds;
+
+  for (int i = 0; i <= this->current_scan->points.size(); i++) {
+    float d = std::sqrt(pow(this->current_scan->points[i].x, 2) + pow(this->current_scan->points[i].y, 2) + pow(this->current_scan->points[i].z, 2));
+    ds.push_back(d);
+  }
+
+  // median
+  std::nth_element(ds.begin(), ds.begin() + ds.size()/2, ds.end());
+  float median_curr = ds[ds.size()/2];
+  static float median_prev = median_curr;
+  float median_lpf = 0.95*median_prev + 0.05*median_curr;
+  median_prev = median_lpf;
+
+  // push
+  this->metrics.spaciousness.push_back( median_lpf );
+
+}
+
+
+/**
+ * Convex Hull of Keyframes
+ **/
+
+void dlo::OdomNode::computeConvexHull() {
+
+  // at least 4 keyframes for convex hull
+  if (this->num_keyframes < 4) {
+    return;
+  }
+
+  // create a pointcloud with points at keyframes
+  pcl::PointCloud<PointType>::Ptr cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+
+  for (const auto& k : this->keyframes) {
+    PointType pt;
+    pt.x = k.first.first[0];
+    pt.y = k.first.first[1];
+    pt.z = k.first.first[2];
+    cloud->push_back(pt);
+  }
+
+  // calculate the convex hull of the point cloud
+  this->convex_hull.setInputCloud(cloud);
+
+  // get the indices of the keyframes on the convex hull
+  pcl::PointCloud<PointType>::Ptr convex_points = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->convex_hull.reconstruct(*convex_points);
+
+  pcl::PointIndices::Ptr convex_hull_point_idx = pcl::PointIndices::Ptr (new pcl::PointIndices);
+  this->convex_hull.getHullPointIndices(*convex_hull_point_idx);
+
+  this->keyframe_convex.clear();
+  for (int i=0; i<convex_hull_point_idx->indices.size(); ++i) {
+    this->keyframe_convex.push_back(convex_hull_point_idx->indices[i]);
+  }
+
+}
+
+
+/**
+ * Concave Hull of Keyframes
+ **/
+
+void dlo::OdomNode::computeConcaveHull() {
+
+  // at least 5 keyframes for concave hull
+  if (this->num_keyframes < 5) {
+    return;
+  }
+
+  // create a pointcloud with points at keyframes
+  pcl::PointCloud<PointType>::Ptr cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+
+  for (const auto& k : this->keyframes) {
+    PointType pt;
+    pt.x = k.first.first[0];
+    pt.y = k.first.first[1];
+    pt.z = k.first.first[2];
+    cloud->push_back(pt);
+  }
+
+  // calculate the concave hull of the point cloud
+  this->concave_hull.setInputCloud(cloud);
+
+  // get the indices of the keyframes on the concave hull
+  pcl::PointCloud<PointType>::Ptr concave_points = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->concave_hull.reconstruct(*concave_points);
+
+  pcl::PointIndices::Ptr concave_hull_point_idx = pcl::PointIndices::Ptr (new pcl::PointIndices);
+  this->concave_hull.getHullPointIndices(*concave_hull_point_idx);
+
+  this->keyframe_concave.clear();
+  for (int i=0; i<concave_hull_point_idx->indices.size(); ++i) {
+    this->keyframe_concave.push_back(concave_hull_point_idx->indices[i]);
+  }
+
+}
+
+
+/**
+ * Update keyframes
+ **/
+
+void dlo::OdomNode::updateKeyframes() {
+
+  // transform point cloud
+  this->transformCurrentScan();
+
+  // calculate difference in pose and rotation to all poses in trajectory
+  float closest_d = std::numeric_limits<float>::infinity();
+  int closest_idx = 0;
+  int keyframes_idx = 0;
+
+  int num_nearby = 0;
+
+  for (const auto& k : this->keyframes) {
+
+    // calculate distance between current pose and pose in keyframes
+    float delta_d = sqrt( pow(this->pose[0] - k.first.first[0], 2) + pow(this->pose[1] - k.first.first[1], 2) + pow(this->pose[2] - k.first.first[2], 2) );
+
+    // count the number nearby current pose
+    if (delta_d <= this->keyframe_thresh_dist_ * 1.5){
+      ++num_nearby;
+    }
+
+    // store into variable
+    if (delta_d < closest_d) {
+      closest_d = delta_d;
+      closest_idx = keyframes_idx;
+    }
+
+    keyframes_idx++;
+
+  }
+
+  // get closest pose and corresponding rotation
+  Eigen::Vector3f closest_pose = this->keyframes[closest_idx].first.first;
+  Eigen::Quaternionf closest_pose_r = this->keyframes[closest_idx].first.second;
+
+  // calculate distance between current pose and closest pose from above
+  float dd = sqrt( pow(this->pose[0] - closest_pose[0], 2) + pow(this->pose[1] - closest_pose[1], 2) + pow(this->pose[2] - closest_pose[2], 2) );
+
+  // calculate difference in orientation
+  Eigen::Quaternionf dq = this->rotq * (closest_pose_r.inverse());
+
+  float theta_rad = atan2(sqrt( pow(dq.x(), 2) + pow(dq.y(), 2) + pow(dq.z(), 2) ), dq.w());
+  float theta_deg = theta_rad * (180.0/M_PI);
+
+  // update keyframe
+  bool newKeyframe = false;
+
+  if (abs(dd) > this->keyframe_thresh_dist_ || abs(theta_deg) > this->keyframe_thresh_rot_) {
+    newKeyframe = true;
+  }
+  if (abs(dd) <= this->keyframe_thresh_dist_) {
+    newKeyframe = false;
+  }
+  if (abs(dd) <= this->keyframe_thresh_dist_ && abs(theta_deg) > this->keyframe_thresh_rot_ && num_nearby <= 1) {
+    newKeyframe = true;
+  }
+
+  if (newKeyframe) {
+
+    ++this->num_keyframes;
+
+    // voxelization for submap
+    if (this->vf_submap_use_) {
+      this->vf_submap.setInputCloud(this->current_scan_t);
+      this->vf_submap.filter(*this->current_scan_t);
+    }
+
+    // update keyframe vector
+    this->keyframes.push_back(std::make_pair(std::make_pair(this->pose, this->rotq), this->current_scan_t));
+
+    // update keyframe normals
+    this->keyframe_normals.push_back(this->gicp_s2s.getSourceCovariances());
+
+    *this->keyframes_cloud += *this->current_scan_t;
+    *this->keyframe_cloud = *this->current_scan_t;
+
+    this->publish_keyframe_thread = std::thread( &dlo::OdomNode::publishKeyframe, this );
+    this->publish_keyframe_thread.detach();
+
+  }
+
+}
+
+
+/**
+ * Set Adaptive Parameters
+ **/
+
+void dlo::OdomNode::setAdaptiveParams() {
+
+  // Set Keyframe Thresh from Spaciousness Metric
+  if (this->metrics.spaciousness.back() > 20.0){
+    this->keyframe_thresh_dist_ = 10.0;
+  } else if (this->metrics.spaciousness.back() > 10.0 && this->metrics.spaciousness.back() <= 20.0) {
+    this->keyframe_thresh_dist_ = 5.0;
+  } else if (this->metrics.spaciousness.back() > 5.0 && this->metrics.spaciousness.back() <= 10.0) {
+    this->keyframe_thresh_dist_ = 1.0;
+  } else if (this->metrics.spaciousness.back() <= 5.0) {
+    this->keyframe_thresh_dist_ = 0.5;
+  }
+
+  // set concave hull alpha
+  this->concave_hull.setAlpha(this->keyframe_thresh_dist_);
+
+}
+
+
+/**
+ * Push Submap Keyframe Indices
+ **/
+void dlo::OdomNode::pushSubmapIndices(std::vector<float> dists, int k) {
+
+  // maintain max heap of at most k elements
+  std::priority_queue<float> pq;
+
+  for (auto d : dists) {
+    if (pq.size() >= k && pq.top() > d) {
+      pq.push(d);
+      pq.pop();
+    } else if (pq.size() < k) {
+      pq.push(d);
+    }
+  }
+
+  // get the kth smallest element, which should be at the top of the heap
+  float kth_element = pq.top();
+
+  // get all elements smaller or equal to the kth smallest element
+  for (int i = 0; i < dists.size(); ++i) {
+    if (dists[i] <= kth_element)
+      this->submap_kf_idx_curr.push_back(i);
+  }
+
+}
+
+
+/**
+ * Get Submap using Nearest Neighbor Keyframes
+ **/
+
+void dlo::OdomNode::getSubmapKeyframes() {
+
+  // reinitialize submap cloud and normals
+  this->submap_cloud = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType>);
+  this->submap_normals.clear();
+
+  // clear vector of keyframe indices to use for submap
+  this->submap_kf_idx_curr.clear();
+
+  //
+  // TOP K NEAREST NEIGHBORS FROM ALL KEYFRAMES
+  //
+
+  // calculate distance between current pose and poses in keyframe set
+  std::vector<float> ds;
+  for (const auto& k : this->keyframes) {
+    float d = sqrt( pow(this->pose[0] - k.first.first[0], 2) + pow(this->pose[1] - k.first.first[1], 2) + pow(this->pose[2] - k.first.first[2], 2) );
+    ds.push_back(d);
+  }
+
+  // get indices for top K nearest neighbor keyframe poses
+  this->pushSubmapIndices(ds, this->submap_knn_);
+
+  //
+  // TOP K NEAREST NEIGHBORS FROM CONVEX HULL
+  //
+
+  // get convex hull indices
+  this->computeConvexHull();
+
+  // get distances for each keyframe on convex hull
+  std::vector<float> convex_ds;
+  for (const auto& c : this->keyframe_convex) {
+    convex_ds.push_back(ds[c]);
+  }
+
+  // get indicies for top kNN for convex hull
+  this->pushSubmapIndices(convex_ds, this->submap_kcv_);
+
+  //
+  // TOP K NEAREST NEIGHBORS FROM CONCAVE HULL
+  //
+
+  // get concave hull indices
+  this->computeConcaveHull();
+
+  // get distances for each keyframe on concave hull
+  std::vector<float> concave_ds;
+  for (const auto& c : this->keyframe_concave) {
+    concave_ds.push_back(ds[c]);
+  }
+
+  // get indicies for top kNN for convex hull
+  this->pushSubmapIndices(concave_ds, this->submap_kcc_);
+
+  //
+  // BUILD SUBMAP
+  //
+
+  // concatenate all submap clouds and normals
+  std::sort(this->submap_kf_idx_curr.begin(), this->submap_kf_idx_curr.end());
+  auto last = std::unique(this->submap_kf_idx_curr.begin(), this->submap_kf_idx_curr.end());
+  this->submap_kf_idx_curr.erase(last, this->submap_kf_idx_curr.end());
+  for (auto k : this->submap_kf_idx_curr) {
+
+    // create current submap cloud
+    *this->submap_cloud += *this->keyframes[k].second;
+
+    // grab corresponding submap cloud's normals
+    this->submap_normals.insert( std::end(this->submap_normals), std::begin(this->keyframe_normals[k]), std::end(this->keyframe_normals[k]) );
+
+  }
+
+  // sort current and previous submap kf list of indices
+  std::sort(this->submap_kf_idx_curr.begin(), this->submap_kf_idx_curr.end());
+  std::sort(this->submap_kf_idx_prev.begin(), this->submap_kf_idx_prev.end());
+
+  // check if submap has changed from previous iteration
+  if(this->submap_kf_idx_curr == this->submap_kf_idx_prev){
+    this->submap_hasChanged = false;
+  } else{
+    this->submap_hasChanged = true;
+  }
+
+  this->submap_kf_idx_prev = this->submap_kf_idx_curr;
+}
+
+
+/**
+ * Debug Statements
+ **/
+
+void dlo::OdomNode::debug() {
+
+  // Total length traversed
+  double length_traversed = 0.;
+  Eigen::Vector3f p_curr = Eigen::Vector3f(0., 0., 0.);
+  Eigen::Vector3f p_prev = Eigen::Vector3f(0., 0., 0.);
+  for (const auto& t : this->trajectory) {
+    if (p_prev == Eigen::Vector3f(0., 0., 0.)) {
+      p_prev = t.first;
+      continue;
+    }
+    p_curr = t.first;
+    double l = sqrt(pow(p_curr[0] - p_prev[0], 2) + pow(p_curr[1] - p_prev[1], 2) + pow(p_curr[2] - p_prev[2], 2));
+
+    if (l >= 0.05) {
+      length_traversed += l;
+      p_prev = p_curr;
+    }
+  }
+
+  if (length_traversed == 0) {
+    this->publish_keyframe_thread = std::thread( &dlo::OdomNode::publishKeyframe, this );
+    this->publish_keyframe_thread.detach();
+  }
+
+  // Average computation time
+  double avg_comp_time = std::accumulate(this->comp_times.begin(), this->comp_times.end(), 0.0) / this->comp_times.size();
+
+  // RAM Usage
+  double vm_usage = 0.0;
+  double resident_set = 0.0;
+  std::ifstream stat_stream("/proc/self/stat", std::ios_base::in); //get info from proc directory
+  std::string pid, comm, state, ppid, pgrp, session, tty_nr;
+  std::string tpgid, flags, minflt, cminflt, majflt, cmajflt;
+  std::string utime, stime, cutime, cstime, priority, nice;
+  std::string num_threads, itrealvalue, starttime;
+  unsigned long vsize;
+  long rss;
+  stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
+              >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
+              >> utime >> stime >> cutime >> cstime >> priority >> nice
+              >> num_threads >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
+  stat_stream.close();
+  long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // for x86-64 is configured to use 2MB pages
+  vm_usage = vsize / 1024.0;
+  resident_set = rss * page_size_kb;
+
+  // CPU Usage
+  struct tms timeSample;
+  clock_t now;
+  double cpu_percent;
+  now = times(&timeSample);
+  if (now <= this->lastCPU || timeSample.tms_stime < this->lastSysCPU ||
+      timeSample.tms_utime < this->lastUserCPU) {
+      cpu_percent = -1.0;
+  } else {
+      cpu_percent = (timeSample.tms_stime - this->lastSysCPU) + (timeSample.tms_utime - this->lastUserCPU);
+      cpu_percent /= (now - this->lastCPU);
+      cpu_percent /= this->numProcessors;
+      cpu_percent *= 100.;
+  }
+  this->lastCPU = now;
+  this->lastSysCPU = timeSample.tms_stime;
+  this->lastUserCPU = timeSample.tms_utime;
+  this->cpu_percents.push_back(cpu_percent);
+  double avg_cpu_usage = std::accumulate(this->cpu_percents.begin(), this->cpu_percents.end(), 0.0) / this->cpu_percents.size();
+
+  // Print to terminal
+  printf("\033[2J\033[1;1H");
+
+  std::cout << std::endl << "==== Direct LiDAR Odometry v" << this->version_ << " ====" << std::endl;
+
+  std::cout << std::endl << this->cpu_type << " x " << this->numProcessors << std::endl;
+
+  std::cout << std::endl << std::setprecision(4) << std::fixed;
+  std::cout << "Position    [xyz]  :: " << this->pose[0] << " " << this->pose[1] << " " << this->pose[2] << std::endl;
+  std::cout << "Orientation [wxyz] :: " << this->rotq.w() << " " << this->rotq.x() << " " << this->rotq.y() << " " << this->rotq.z() << std::endl;
+  std::cout << "Distance Traveled  :: " << length_traversed << " meters" << std::endl;
+  std::cout << "Distance to Origin :: " << sqrt(pow(this->pose[0],2) + pow(this->pose[1],2) + pow(this->pose[2],2)) << " meters" << std::endl;
+
+  std::cout << std::endl << std::right << std::setprecision(2) << std::fixed;
+  std::cout << "Computation Time :: " << std::setfill(' ') << std::setw(6) << this->comp_times.back()*1000. << " ms    // Avg: " << std::setw(5) << avg_comp_time*1000. << std::endl;
+  std::cout << "Cores Utilized   :: " << std::setfill(' ') << std::setw(6) << (cpu_percent/100.) * this->numProcessors << " cores // Avg: " << std::setw(5) << (avg_cpu_usage/100.) * this->numProcessors << std::endl;
+  std::cout << "CPU Load         :: " << std::setfill(' ') << std::setw(6) << cpu_percent << " %     // Avg: " << std::setw(5) << avg_cpu_usage << std::endl;
+  std::cout << "RAM Allocation   :: " << std::setfill(' ') << std::setw(6) << resident_set/1000. << " MB    // VSZ: " << vm_usage/1000. << " MB" << std::endl;
+
+}
+sensor_msgs::Imu dlo::OdomNode::imuConverter(const sensor_msgs::Imu& imu_in)
+{
+    sensor_msgs::Imu imu_out = imu_in;
+    // rotate acceleration
+    Eigen::Vector3d acc(imu_in.linear_acceleration.x, imu_in.linear_acceleration.y, imu_in.linear_acceleration.z);
+    acc = extRot * acc;
+    imu_out.linear_acceleration.x = acc.x();
+    imu_out.linear_acceleration.y = acc.y();
+    imu_out.linear_acceleration.z = acc.z();
+    // rotate gyroscope
+    Eigen::Vector3d gyr(imu_in.angular_velocity.x, imu_in.angular_velocity.y, imu_in.angular_velocity.z);
+    gyr = extRot * gyr;
+    imu_out.angular_velocity.x = gyr.x();
+    imu_out.angular_velocity.y = gyr.y();
+    imu_out.angular_velocity.z = gyr.z();
+    // rotate roll pitch yaw
+    Eigen::Quaterniond q_from(imu_in.orientation.w, imu_in.orientation.x, imu_in.orientation.y, imu_in.orientation.z);
+    Eigen::Quaterniond q_final = q_from * extQRPY;
+    imu_out.orientation.x = q_final.x();
+    imu_out.orientation.y = q_final.y();
+    imu_out.orientation.z = q_final.z();
+    imu_out.orientation.w = q_final.w();
+
+//    if (sqrt(q_final.x()*q_final.x() + q_final.y()*q_final.y() + q_final.z()*q_final.z() + q_final.w()*q_final.w()) < 0.1)
+//    {
+//        ROS_ERROR("Invalid quaternion, please use a 9-axis IMU!");
+//        ros::shutdown();
+//    }
+
+    return imu_out;
+}

+ 34 - 0
src/dlo/odom_node.cc

@@ -0,0 +1,34 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+#include "dlo/odom.h"
+
+void controlC(int sig) {
+
+  dlo::OdomNode::abort();
+
+}
+
+int main(int argc, char** argv) {
+
+  ros::init(argc, argv, "dlo_odom_node");
+  ros::NodeHandle nh("~");
+
+  signal(SIGTERM, controlC);
+  sleep(0.5);
+
+  dlo::OdomNode node(nh);
+  ros::AsyncSpinner spinner(0);
+  spinner.start();
+  node.start();
+  ros::waitForShutdown();
+
+  return 0;
+
+}

+ 46 - 0
src/nano_gicp/lsq_registration.cc

@@ -0,0 +1,46 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#include <dlo/dlo.h>
+#include <nano_gicp/lsq_registration.hpp>
+#include <nano_gicp/impl/lsq_registration_impl.hpp>
+
+template class nano_gicp::LsqRegistration<PointType, PointType>;

+ 46 - 0
src/nano_gicp/nano_gicp.cc

@@ -0,0 +1,46 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * BSD 3-Clause License
+ * 
+ * Copyright (c) 2020, SMRT-AIST
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ *    list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ * 
+ * 3. Neither the name of the copyright holder nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#include <dlo/dlo.h>
+#include <nano_gicp/nano_gicp.hpp>
+#include <nano_gicp/impl/nano_gicp_impl.hpp>
+
+template class nano_gicp::NanoGICP<PointType, PointType>;

+ 46 - 0
src/nano_gicp/nanoflann.cc

@@ -0,0 +1,46 @@
+/************************************************************
+ *
+ * Copyright (c) 2021, University of California, Los Angeles
+ *
+ * Authors: Kenny J. Chen, Brett T. Lopez
+ * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu
+ *
+ ***********************************************************/
+
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ * Copyright 2011-2021  Jose Luis Blanco (joseluisblancoc@gmail.com).
+ *   All rights reserved.
+ *
+ * THE BSD LICENSE
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#include <dlo/dlo.h>
+#include <nano_gicp/nanoflann.hpp>
+#include <nano_gicp/impl/nanoflann_impl.hpp>
+
+template class nanoflann::KdTreeFLANN<PointType>;

Some files were not shown because too many files changed in this diff