/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 *  @file  TestSmartStereoProjectionPoseFactor.cpp
 *  @brief Unit tests for ProjectionFactor Class
 *  @author Chris Beall
 *  @author Luca Carlone
 *  @author Zsolt Kira
 *  @date   Sept 2013
 */

#include <gtsam/slam/tests/smartFactorScenarios.h>
#include <gtsam_unstable/slam/SmartStereoProjectionPoseFactor.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/slam/PoseTranslationPrior.h>
#include <gtsam/slam/ProjectionFactor.h>
#include <gtsam/slam/StereoFactor.h>
#include <boost/assign/std/vector.hpp>
#include <CppUnitLite/TestHarness.h>
#include <iostream>

using namespace std;
using namespace boost::assign;
using namespace gtsam;

// make a realistic calibration matrix
static double b = 1;

static Cal3_S2Stereo::shared_ptr K(new Cal3_S2Stereo(fov, w, h, b));
static Cal3_S2Stereo::shared_ptr K2(
    new Cal3_S2Stereo(1500, 1200, 0, 640, 480, b));

static SmartStereoProjectionParams params;

// static bool manageDegeneracy = true;
// Create a noise model for the pixel error
static SharedNoiseModel model(noiseModel::Isotropic::Sigma(3, 0.1));

// Convenience for named keys
using symbol_shorthand::X;
using symbol_shorthand::L;

// tests data
static Symbol x1('X', 1);
static Symbol x2('X', 2);
static Symbol x3('X', 3);

static Key poseKey1(x1);
static StereoPoint2 measurement1(323.0, 300.0, 240.0); //potentially use more reasonable measurement value?
static Pose3 body_P_sensor1(Rot3::RzRyRx(-M_PI_2, 0.0, -M_PI_2),
    Point3(0.25, -0.10, 1.0));

static double missing_uR = std::numeric_limits<double>::quiet_NaN();

vector<StereoPoint2> stereo_projectToMultipleCameras(const StereoCamera& cam1,
    const StereoCamera& cam2, const StereoCamera& cam3, Point3 landmark) {

  vector<StereoPoint2> measurements_cam;

  StereoPoint2 cam1_uv1 = cam1.project(landmark);
  StereoPoint2 cam2_uv1 = cam2.project(landmark);
  StereoPoint2 cam3_uv1 = cam3.project(landmark);
  measurements_cam.push_back(cam1_uv1);
  measurements_cam.push_back(cam2_uv1);
  measurements_cam.push_back(cam3_uv1);

  return measurements_cam;
}

LevenbergMarquardtParams lm_params;

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, params) {
  SmartStereoProjectionParams p;

  // check default values and "get"
  EXPECT(p.getLinearizationMode() == HESSIAN);
  EXPECT(p.getDegeneracyMode() == IGNORE_DEGENERACY);
  EXPECT_DOUBLES_EQUAL(p.getRetriangulationThreshold(), 1e-5, 1e-9);
  EXPECT(p.getVerboseCheirality() == false);
  EXPECT(p.getThrowCheirality() == false);

  // check "set"
  p.setLinearizationMode(JACOBIAN_SVD);
  p.setDegeneracyMode(ZERO_ON_DEGENERACY);
  p.setRankTolerance(100);
  p.setEnableEPI(true);
  p.setLandmarkDistanceThreshold(200);
  p.setDynamicOutlierRejectionThreshold(3);
  p.setRetriangulationThreshold(1e-2);

  EXPECT(p.getLinearizationMode() == JACOBIAN_SVD);
  EXPECT(p.getDegeneracyMode() == ZERO_ON_DEGENERACY);
  EXPECT_DOUBLES_EQUAL(p.getTriangulationParameters().rankTolerance, 100, 1e-5);
  EXPECT(p.getTriangulationParameters().enableEPI == true);
  EXPECT_DOUBLES_EQUAL(p.getTriangulationParameters().landmarkDistanceThreshold, 200, 1e-5);
  EXPECT_DOUBLES_EQUAL(p.getTriangulationParameters().dynamicOutlierRejectionThreshold, 3, 1e-5);
  EXPECT_DOUBLES_EQUAL(p.getRetriangulationThreshold(), 1e-2, 1e-5);
}

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, Constructor) {
  SmartStereoProjectionPoseFactor::shared_ptr factor1(new SmartStereoProjectionPoseFactor(model));
}

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, Constructor2) {
  SmartStereoProjectionPoseFactor factor1(model, params);
}

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, Constructor3) {
  SmartStereoProjectionPoseFactor::shared_ptr factor1(new SmartStereoProjectionPoseFactor(model));
  factor1->add(measurement1, poseKey1, K);
}

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, Constructor4) {
  SmartStereoProjectionPoseFactor factor1(model, params);
  factor1.add(measurement1, poseKey1, K);
}

/* ************************************************************************* */
TEST( SmartStereoProjectionPoseFactor, Equals ) {
  SmartStereoProjectionPoseFactor::shared_ptr factor1(new SmartStereoProjectionPoseFactor(model));
  factor1->add(measurement1, poseKey1, K);

  SmartStereoProjectionPoseFactor::shared_ptr factor2(new SmartStereoProjectionPoseFactor(model));
  factor2->add(measurement1, poseKey1, K);

  CHECK(assert_equal(*factor1, *factor2));
}

/* *************************************************************************/
TEST_UNSAFE( SmartStereoProjectionPoseFactor, noiseless ) {
  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 level_pose = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2),
      Point3(0, 0, 1));
  StereoCamera level_camera(level_pose, K2);

  // create second camera 1 meter to the right of first camera
  Pose3 level_pose_right = level_pose * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera level_camera_right(level_pose_right, K2);

  // landmark ~5 meters infront of camera
  Point3 landmark(5, 0.5, 1.2);

  // 1. Project two landmarks into two cameras and triangulate
  StereoPoint2 level_uv = level_camera.project(landmark);
  StereoPoint2 level_uv_right = level_camera_right.project(landmark);

  Values values;
  values.insert(x1, level_pose);
  values.insert(x2, level_pose_right);

  SmartStereoProjectionPoseFactor factor1(model);
  factor1.add(level_uv, x1, K2);
  factor1.add(level_uv_right, x2, K2);

  double actualError = factor1.error(values);
  double expectedError = 0.0;
  EXPECT_DOUBLES_EQUAL(expectedError, actualError, 1e-7);

  SmartStereoProjectionPoseFactor::Cameras cameras = factor1.cameras(values);
  double actualError2 = factor1.totalReprojectionError(cameras);
  EXPECT_DOUBLES_EQUAL(expectedError, actualError2, 1e-7);

  // test vector of errors
  //Vector actual = factor1.unwhitenedError(values);
  //EXPECT(assert_equal(zero(4),actual,1e-8));
}

/* *************************************************************************/
TEST( SmartProjectionPoseFactor, noiselessWithMissingMeasurements ) {

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
   Pose3 level_pose = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2),
       Point3(0, 0, 1));
   StereoCamera level_camera(level_pose, K2);

   // create second camera 1 meter to the right of first camera
   Pose3 level_pose_right = level_pose * Pose3(Rot3(), Point3(1, 0, 0));
   StereoCamera level_camera_right(level_pose_right, K2);

   // landmark ~5 meters in front of camera
   Point3 landmark(5, 0.5, 1.2);

   // 1. Project two landmarks into two cameras and triangulate
   StereoPoint2 level_uv = level_camera.project(landmark);
   StereoPoint2 level_uv_right = level_camera_right.project(landmark);
   StereoPoint2 level_uv_right_missing(level_uv_right.uL(),missing_uR,level_uv_right.v());

   Values values;
   values.insert(x1, level_pose);
   values.insert(x2, level_pose_right);

   SmartStereoProjectionPoseFactor factor1(model);
   factor1.add(level_uv, x1, K2);
   factor1.add(level_uv_right_missing, x2, K2);

   double actualError = factor1.error(values);
   double expectedError = 0.0;
   EXPECT_DOUBLES_EQUAL(expectedError, actualError, 1e-7);

   // TEST TRIANGULATION WITH MISSING VALUES: i) right pixel of second camera is missing:
   SmartStereoProjectionPoseFactor::Cameras cameras = factor1.cameras(values);
   double actualError2 = factor1.totalReprojectionError(cameras);
   EXPECT_DOUBLES_EQUAL(expectedError, actualError2, 1e-7);

   CameraSet<StereoCamera> cams;
   cams += level_camera;
   cams += level_camera_right;
   TriangulationResult result = factor1.triangulateSafe(cams);
   CHECK(result);
   EXPECT(assert_equal(landmark, *result, 1e-7));

   // TEST TRIANGULATION WITH MISSING VALUES: ii) right pixels of both cameras are missing:
   SmartStereoProjectionPoseFactor factor2(model);
   StereoPoint2 level_uv_missing(level_uv.uL(),missing_uR,level_uv.v());
   factor2.add(level_uv_missing, x1, K2);
   factor2.add(level_uv_right_missing, x2, K2);
   result = factor2.triangulateSafe(cams);
   CHECK(result);
   EXPECT(assert_equal(landmark, *result, 1e-7));
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, noisy ) {
  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 level_pose = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2),
      Point3(0, 0, 1));
  StereoCamera level_camera(level_pose, K2);

  // create second camera 1 meter to the right of first camera
  Pose3 level_pose_right = level_pose * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera level_camera_right(level_pose_right, K2);

  // landmark ~5 meters infront of camera
  Point3 landmark(5, 0.5, 1.2);

  // 1. Project two landmarks into two cameras and triangulate
  StereoPoint2 pixelError(0.2, 0.2, 0);
  StereoPoint2 level_uv = level_camera.project(landmark) + pixelError;
  StereoPoint2 level_uv_right = level_camera_right.project(landmark);

  Values values;
  values.insert(x1, level_pose);
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 10, 0., -M_PI / 10),
      Point3(0.5, 0.1, 0.3));
  values.insert(x2, level_pose_right.compose(noise_pose));

  SmartStereoProjectionPoseFactor::shared_ptr factor1(new SmartStereoProjectionPoseFactor(model));
  factor1->add(level_uv, x1, K);
  factor1->add(level_uv_right, x2, K);

  double actualError1 = factor1->error(values);

  SmartStereoProjectionPoseFactor::shared_ptr factor2(new SmartStereoProjectionPoseFactor(model));
  vector<StereoPoint2> measurements;
  measurements.push_back(level_uv);
  measurements.push_back(level_uv_right);

  vector<std::shared_ptr<Cal3_S2Stereo> > Ks; ///< shared pointer to calibration object (one for each camera)
  Ks.push_back(K);
  Ks.push_back(K);

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);

  factor2->add(measurements, views, Ks);

  double actualError2 = factor2->error(values);

  DOUBLES_EQUAL(actualError1, actualError2, 1e-7);
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, 3poses_smart_projection_factor ) {

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K2);

  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K2);

  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K2);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // 1. Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_l1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_l2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_l3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  SmartStereoProjectionParams smart_params;
  smart_params.triangulation.enableEPI = true;
  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(model, smart_params));
  smartFactor1->add(measurements_l1, views, K2);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, smart_params));
  smartFactor2->add(measurements_l2, views, K2);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, smart_params));
  smartFactor3->add(measurements_l3, views, K2);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.emplace_shared<PriorFactor<Pose3> >(x1, pose1, noisePrior);
  graph.emplace_shared<PriorFactor<Pose3> >(x2, pose2, noisePrior);

  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  // initialize third pose with some noise, we expect it to move back to original pose3
  values.insert(x3, pose3 * noise_pose);
  EXPECT(
      assert_equal(
          Pose3(
              Rot3(0, -0.0314107591, 0.99950656, -0.99950656, -0.0313952598,
                  -0.000986635786, 0.0314107591, -0.999013364, -0.0313952598),
              Point3(0.1, -0.1, 1.9)), values.at<Pose3>(x3)));

  //  cout << std::setprecision(10) << "\n----SmartStereoFactor graph initial error: " << graph.error(values) << endl;
  EXPECT_DOUBLES_EQUAL(833953.92789459578, graph.error(values), 1e-7); // initial error

  // get triangulated landmarks from smart factors
  Point3 landmark1_smart = *smartFactor1->point();
  Point3 landmark2_smart = *smartFactor2->point();
  Point3 landmark3_smart = *smartFactor3->point();

  Values result;
  gttic_(SmartStereoProjectionPoseFactor);
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  gttoc_(SmartStereoProjectionPoseFactor);
  tictoc_finishedIteration_();

  EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-5);

//  cout << std::setprecision(10) << "SmartStereoFactor graph optimized error: " << graph.error(result) << endl;

  GaussianFactorGraph::shared_ptr GFG = graph.linearize(result);
  VectorValues delta = GFG->optimize();
  VectorValues expected = VectorValues::Zero(delta);
  EXPECT(assert_equal(expected, delta, 1e-6));

  // result.print("results of 3 camera, 3 landmark optimization \n");
  EXPECT(assert_equal(pose3, result.at<Pose3>(x3)));

  /* ***************************************************************
   * Same problem with regular Stereo factors, expect same error!
   * ****************************************************************/

//  landmark1_smart.print("landmark1_smart");
//  landmark2_smart.print("landmark2_smart");
//  landmark3_smart.print("landmark3_smart");

  // add landmarks to values
  values.insert(L(1), landmark1_smart);
  values.insert(L(2), landmark2_smart);
  values.insert(L(3), landmark3_smart);

  // add factors
  NonlinearFactorGraph graph2;

  graph2.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
  graph2.push_back(PriorFactor<Pose3>(x2, pose2, noisePrior));

  typedef GenericStereoFactor<Pose3, Point3> ProjectionFactor;

  bool verboseCheirality = true;

  graph2.push_back(ProjectionFactor(measurements_l1[0], model, x1, L(1), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l1[1], model, x2, L(1), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l1[2], model, x3, L(1), K2, false, verboseCheirality));

  graph2.push_back(ProjectionFactor(measurements_l2[0], model, x1, L(2), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l2[1], model, x2, L(2), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l2[2], model, x3, L(2), K2, false, verboseCheirality));

  graph2.push_back(ProjectionFactor(measurements_l3[0], model, x1, L(3), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l3[1], model, x2, L(3), K2, false, verboseCheirality));
  graph2.push_back(ProjectionFactor(measurements_l3[2], model, x3, L(3), K2, false, verboseCheirality));

//  cout << std::setprecision(10) << "\n----StereoFactor graph initial error: " << graph2.error(values) << endl;
  EXPECT_DOUBLES_EQUAL(833953.92789459578, graph2.error(values), 1e-7);

  LevenbergMarquardtOptimizer optimizer2(graph2, values, lm_params);
  Values result2 = optimizer2.optimize();
  EXPECT_DOUBLES_EQUAL(0, graph2.error(result2), 1e-5);

//  cout << std::setprecision(10) << "StereoFactor graph optimized error: " << graph2.error(result2) << endl;

}
/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, body_P_sensor ) {

  // camera has some displacement
  Pose3 body_P_sensor = Pose3(Rot3::Ypr(-0.01, 0., -0.05), Point3(0.1, 0, 0.1));
  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1.compose(body_P_sensor), K2);

  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2.compose(body_P_sensor), K2);

  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3.compose(body_P_sensor), K2);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // 1. Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_l1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_l2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_l3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  SmartStereoProjectionParams smart_params;
  smart_params.triangulation.enableEPI = true;
  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(model, smart_params, body_P_sensor));
  smartFactor1->add(measurements_l1, views, K2);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, smart_params, body_P_sensor));
  smartFactor2->add(measurements_l2, views, K2);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, smart_params, body_P_sensor));
  smartFactor3->add(measurements_l3, views, K2);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
  graph.push_back(PriorFactor<Pose3>(x2, pose2, noisePrior));

  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  // initialize third pose with some noise, we expect it to move back to original pose3
  values.insert(x3, pose3 * noise_pose);
  EXPECT(
      assert_equal(
          Pose3(
              Rot3(0, -0.0314107591, 0.99950656, -0.99950656, -0.0313952598,
                  -0.000986635786, 0.0314107591, -0.999013364, -0.0313952598),
              Point3(0.1, -0.1, 1.9)), values.at<Pose3>(x3)));

  //  cout << std::setprecision(10) << "\n----SmartStereoFactor graph initial error: " << graph.error(values) << endl;
  EXPECT_DOUBLES_EQUAL(953392.32838422502, graph.error(values), 1e-7); // initial error

  Values result;
  gttic_(SmartStereoProjectionPoseFactor);
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  gttoc_(SmartStereoProjectionPoseFactor);
  tictoc_finishedIteration_();

  EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-5);

  // result.print("results of 3 camera, 3 landmark optimization \n");
  EXPECT(assert_equal(pose3, result.at<Pose3>(x3)));
}
/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, body_P_sensor_monocular ){
  // make a realistic calibration matrix
  double fov = 60; // degrees
  size_t w=640,h=480;

  Cal3_S2::shared_ptr K(new Cal3_S2(fov,w,h));

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 cameraPose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), gtsam::Point3(0,0,1)); // body poses
  Pose3 cameraPose2 = cameraPose1 * Pose3(Rot3(), Point3(1,0,0));
  Pose3 cameraPose3 = cameraPose1 * Pose3(Rot3(), Point3(0,-1,0));

  SimpleCamera cam1(cameraPose1, *K); // with camera poses
  SimpleCamera cam2(cameraPose2, *K);
  SimpleCamera cam3(cameraPose3, *K);

  // create arbitrary body_Pose_sensor (transforms from sensor to body)
  Pose3 sensor_to_body =  Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), gtsam::Point3(1, 1, 1)); // Pose3(); //

  // These are the poses we want to estimate, from camera measurements
  Pose3 bodyPose1 = cameraPose1.compose(sensor_to_body.inverse());
  Pose3 bodyPose2 = cameraPose2.compose(sensor_to_body.inverse());
  Pose3 bodyPose3 = cameraPose3.compose(sensor_to_body.inverse());

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(5, 0, 3.0);

  Point2Vector measurements_cam1, measurements_cam2, measurements_cam3;

  // Project three landmarks into three cameras
  projectToMultipleCameras(cam1, cam2, cam3, landmark1, measurements_cam1);
  projectToMultipleCameras(cam1, cam2, cam3, landmark2, measurements_cam2);
  projectToMultipleCameras(cam1, cam2, cam3, landmark3, measurements_cam3);

  // Create smart factors
  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // convert measurement to (degenerate) stereoPoint2 (with right pixel being NaN)
  vector<StereoPoint2> measurements_cam1_stereo, measurements_cam2_stereo, measurements_cam3_stereo;
  for(size_t k=0; k<measurements_cam1.size();k++)
	  measurements_cam1_stereo.push_back(StereoPoint2(measurements_cam1[k].x() , missing_uR , measurements_cam1[k].y()));

  for(size_t k=0; k<measurements_cam2.size();k++)
	  measurements_cam2_stereo.push_back(StereoPoint2(measurements_cam2[k].x() , missing_uR , measurements_cam2[k].y()));

  for(size_t k=0; k<measurements_cam3.size();k++)
	  measurements_cam3_stereo.push_back(StereoPoint2(measurements_cam3[k].x() , missing_uR , measurements_cam3[k].y()));

  SmartStereoProjectionParams params;
  params.setRankTolerance(1.0);
  params.setDegeneracyMode(gtsam::IGNORE_DEGENERACY);
  params.setEnableEPI(false);

  Cal3_S2Stereo::shared_ptr Kmono(new Cal3_S2Stereo(fov,w,h,b));
  SmartStereoProjectionPoseFactor smartFactor1(model, params, sensor_to_body);
  smartFactor1.add(measurements_cam1_stereo, views, Kmono);

  SmartStereoProjectionPoseFactor smartFactor2(model, params, sensor_to_body);
  smartFactor2.add(measurements_cam2_stereo, views, Kmono);

  SmartStereoProjectionPoseFactor smartFactor3(model, params, sensor_to_body);
  smartFactor3.add(measurements_cam3_stereo, views, Kmono);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  // Put all factors in factor graph, adding priors
  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.push_back(PriorFactor<Pose3>(x1, bodyPose1, noisePrior));
  graph.push_back(PriorFactor<Pose3>(x2, bodyPose2, noisePrior));

  // Check errors at ground truth poses
  Values gtValues;
  gtValues.insert(x1, bodyPose1);
  gtValues.insert(x2, bodyPose2);
  gtValues.insert(x3, bodyPose3);
  double actualError = graph.error(gtValues);
  double expectedError = 0.0;
  DOUBLES_EQUAL(expectedError, actualError, 1e-7)

  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/100, 0., -M_PI/100), gtsam::Point3(0.1,0.1,0.1));
  Values values;
  values.insert(x1, bodyPose1);
  values.insert(x2, bodyPose2);
  // initialize third pose with some noise, we expect it to move back to original pose3
  values.insert(x3, bodyPose3*noise_pose);

  LevenbergMarquardtParams lmParams;
  Values result;
  LevenbergMarquardtOptimizer optimizer(graph, values, lmParams);
  result = optimizer.optimize();
  EXPECT(assert_equal(bodyPose3,result.at<Pose3>(x3)));
}
/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, jacobianSVD ) {

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);
  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K);
  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // 1. Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_cam2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_cam3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  SmartStereoProjectionParams params;
  params.setLinearizationMode(JACOBIAN_SVD);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1( new SmartStereoProjectionPoseFactor(model, params));
  smartFactor1->add(measurements_cam1, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor2->add(measurements_cam2, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor3->add(measurements_cam3, views, K);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.emplace_shared<PriorFactor<Pose3> >(x1, pose1, noisePrior);
  graph.emplace_shared<PriorFactor<Pose3> >(x2, pose2, noisePrior);

  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3 * noise_pose);

  Values result;
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  EXPECT(assert_equal(pose3, result.at<Pose3>(x3)));
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, jacobianSVDwithMissingValues ) {

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);
  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K);
  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // 1. Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_cam2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_cam3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  // DELETE SOME MEASUREMENTS
  StereoPoint2 sp = measurements_cam1[1];
  measurements_cam1[1] = StereoPoint2(sp.uL(), missing_uR, sp.v());
  sp = measurements_cam2[2];
  measurements_cam2[2] = StereoPoint2(sp.uL(), missing_uR, sp.v());

  SmartStereoProjectionParams params;
  params.setLinearizationMode(JACOBIAN_SVD);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1( new SmartStereoProjectionPoseFactor(model, params));
  smartFactor1->add(measurements_cam1, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor2->add(measurements_cam2, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor3->add(measurements_cam3, views, K);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
  graph.push_back(PriorFactor<Pose3>(x2, pose2, noisePrior));

  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3 * noise_pose);

  Values result;
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  EXPECT(assert_equal(pose3, result.at<Pose3>(x3),1e-7));
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, landmarkDistance ) {

//  double excludeLandmarksFutherThanDist = 2;

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);
  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K);
  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // 1. Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_cam2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_cam3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  SmartStereoProjectionParams params;
  params.setLinearizationMode(JACOBIAN_SVD);
  params.setLandmarkDistanceThreshold(2);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor1->add(measurements_cam1, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor2->add(measurements_cam2, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor3->add(measurements_cam3, views, K);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.emplace_shared<PriorFactor<Pose3> >(x1, pose1, noisePrior);
  graph.emplace_shared<PriorFactor<Pose3> >(x2, pose2, noisePrior);

  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3 * noise_pose);

  // All factors are disabled and pose should remain where it is
  Values result;
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  EXPECT(assert_equal(values.at<Pose3>(x3), result.at<Pose3>(x3)));
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, dynamicOutlierRejection ) {

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);
  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K);
  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);
  Point3 landmark4(5, -0.5, 1);

  // 1. Project four landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_cam2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_cam3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);
  vector<StereoPoint2> measurements_cam4 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark4);

  measurements_cam4.at(0) = measurements_cam4.at(0) + StereoPoint2(10, 10, 1); // add outlier

  SmartStereoProjectionParams params;
  params.setLinearizationMode(JACOBIAN_SVD);
  params.setDynamicOutlierRejectionThreshold(1);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor1->add(measurements_cam1, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor2->add(measurements_cam2, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor3->add(measurements_cam3, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor4(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor4->add(measurements_cam4, views, K);

  // same as factor 4, but dynamic outlier rejection is off
  SmartStereoProjectionPoseFactor::shared_ptr smartFactor4b(new SmartStereoProjectionPoseFactor(model));
  smartFactor4b->add(measurements_cam4, views, K);

  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);

  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);
  graph.push_back(smartFactor4);
  graph.emplace_shared<PriorFactor<Pose3> >(x1, pose1, noisePrior);
  graph.emplace_shared<PriorFactor<Pose3> >(x2, pose2, noisePrior);

  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3);

  EXPECT_DOUBLES_EQUAL(0, smartFactor1->error(values), 1e-9);
  EXPECT_DOUBLES_EQUAL(0, smartFactor2->error(values), 1e-9);
  EXPECT_DOUBLES_EQUAL(0, smartFactor3->error(values), 1e-9);
  // zero error due to dynamic outlier rejection
  EXPECT_DOUBLES_EQUAL(0, smartFactor4->error(values), 1e-9);

  // dynamic outlier rejection is off
  EXPECT_DOUBLES_EQUAL(6147.3947317473921, smartFactor4b->error(values), 1e-9);

  // Factors 1-3 should have valid point, factor 4 should not
  EXPECT(smartFactor1->point());
  EXPECT(smartFactor2->point());
  EXPECT(smartFactor3->point());
  EXPECT(smartFactor4->point().outlier());
  EXPECT(smartFactor4b->point());

  // Factor 4 is disabled, pose 3 stays put
  Values result;
  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
  result = optimizer.optimize();
  EXPECT(assert_equal(pose3, result.at<Pose3>(x3)));
}
//
///* *************************************************************************/
//TEST( SmartStereoProjectionPoseFactor, jacobianQ ){
//
//  KeyVector views;
//  views.push_back(x1);
//  views.push_back(x2);
//  views.push_back(x3);
//
//  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
//  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), Point3(0,0,1));
//  StereoCamera cam1(pose1, K);
//  // create second camera 1 meter to the right of first camera
//  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1,0,0));
//  StereoCamera cam2(pose2, K);
//  // create third camera 1 meter above the first camera
//  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0,-1,0));
//  StereoCamera cam3(pose3, K);
//
//  // three landmarks ~5 meters infront of camera
//  Point3 landmark1(5, 0.5, 1.2);
//  Point3 landmark2(5, -0.5, 1.2);
//  Point3 landmark3(3, 0, 3.0);
//
//  vector<StereoPoint2> measurements_cam1, measurements_cam2, measurements_cam3;
//
//  // 1. Project three landmarks into three cameras and triangulate
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark1, measurements_cam1);
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark2, measurements_cam2);
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark3, measurements_cam3);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(1, -1, false, false, JACOBIAN_Q));
//  smartFactor1->add(measurements_cam1, views, model, K);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(1, -1, false, false, JACOBIAN_Q));
//  smartFactor2->add(measurements_cam2, views, model, K);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(1, -1, false, false, JACOBIAN_Q));
//  smartFactor3->add(measurements_cam3, views, model, K);
//
//  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);
//
//  NonlinearFactorGraph graph;
//  graph.push_back(smartFactor1);
//  graph.push_back(smartFactor2);
//  graph.push_back(smartFactor3);
//  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
//  graph.push_back(PriorFactor<Pose3>(x2, pose2, noisePrior));
//
//  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
//  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/100, 0., -M_PI/100), Point3(0.1,0.1,0.1)); // smaller noise
//  Values values;
//  values.insert(x1, pose1);
//  values.insert(x2, pose2);
//  values.insert(x3, pose3*noise_pose);
//
////  Values result;
//  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
//  result = optimizer.optimize();
//  EXPECT(assert_equal(pose3,result.at<Pose3>(x3)));
//}
//
///* *************************************************************************/
//TEST( SmartStereoProjectionPoseFactor, 3poses_projection_factor ){
//
//  KeyVector views;
//  views.push_back(x1);
//  views.push_back(x2);
//  views.push_back(x3);
//
//  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
//  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), Point3(0,0,1));
//  StereoCamera cam1(pose1, K2);
//
//  // create second camera 1 meter to the right of first camera
//  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1,0,0));
//  StereoCamera cam2(pose2, K2);
//
//  // create third camera 1 meter above the first camera
//  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0,-1,0));
//  StereoCamera cam3(pose3, K2);
//
//  // three landmarks ~5 meters infront of camera
//  Point3 landmark1(5, 0.5, 1.2);
//  Point3 landmark2(5, -0.5, 1.2);
//  Point3 landmark3(3, 0, 3.0);
//
//  typedef GenericStereoFactor<Pose3, Point3> ProjectionFactor;
//  NonlinearFactorGraph graph;
//
//  // 1. Project three landmarks into three cameras and triangulate
//  graph.push_back(ProjectionFactor(cam1.project(landmark1), model, x1, L(1), K2));
//  graph.push_back(ProjectionFactor(cam2.project(landmark1), model, x2, L(1), K2));
//  graph.push_back(ProjectionFactor(cam3.project(landmark1), model, x3, L(1), K2));
//
//  graph.push_back(ProjectionFactor(cam1.project(landmark2), model, x1, L(2), K2));
//  graph.push_back(ProjectionFactor(cam2.project(landmark2), model, x2, L(2), K2));
//  graph.push_back(ProjectionFactor(cam3.project(landmark2), model, x3, L(2), K2));
//
//  graph.push_back(ProjectionFactor(cam1.project(landmark3), model, x1, L(3), K2));
//  graph.push_back(ProjectionFactor(cam2.project(landmark3), model, x2, L(3), K2));
//  graph.push_back(ProjectionFactor(cam3.project(landmark3), model, x3, L(3), K2));
//
//  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);
//  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
//  graph.push_back(PriorFactor<Pose3>(x2, pose2, noisePrior));
//
//  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3));
//  Values values;
//  values.insert(x1, pose1);
//  values.insert(x2, pose2);
//  values.insert(x3, pose3* noise_pose);
//  values.insert(L(1), landmark1);
//  values.insert(L(2), landmark2);
//  values.insert(L(3), landmark3);
//
//  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
//  Values result = optimizer.optimize();
//
//  EXPECT(assert_equal(pose3,result.at<Pose3>(x3)));
//}
//
/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, CheckHessian) {

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);

  // create second camera
  Pose3 pose2 = pose1 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0, 0, 0));
  StereoCamera cam2(pose2, K);

  // create third camera
  Pose3 pose3 = pose2 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0, 0, 0));
  StereoCamera cam3(pose3, K);

  // three landmarks ~5 meters infront of camera
  Point3 landmark1(5, 0.5, 1.2);
  Point3 landmark2(5, -0.5, 1.2);
  Point3 landmark3(3, 0, 3.0);

  // Project three landmarks into three cameras and triangulate
  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);
  vector<StereoPoint2> measurements_cam2 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark2);
  vector<StereoPoint2> measurements_cam3 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark3);

  SmartStereoProjectionParams params;
  params.setRankTolerance(10);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor1->add(measurements_cam1, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor2->add(measurements_cam2, views, K);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(model, params));
  smartFactor3->add(measurements_cam3, views, K);

  // Create graph to optimize
  NonlinearFactorGraph graph;
  graph.push_back(smartFactor1);
  graph.push_back(smartFactor2);
  graph.push_back(smartFactor3);

  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  // initialize third pose with some noise, we expect it to move back to original pose3
  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI / 100, 0., -M_PI / 100),
      Point3(0.1, 0.1, 0.1)); // smaller noise
  values.insert(x3, pose3 * noise_pose);

  // TODO: next line throws Cheirality exception on Mac
  std::shared_ptr<GaussianFactor> hessianFactor1 = smartFactor1->linearize(
      values);
  std::shared_ptr<GaussianFactor> hessianFactor2 = smartFactor2->linearize(
      values);
  std::shared_ptr<GaussianFactor> hessianFactor3 = smartFactor3->linearize(
      values);

  Matrix CumulativeInformation = hessianFactor1->information()
      + hessianFactor2->information() + hessianFactor3->information();

  std::shared_ptr<GaussianFactorGraph> GaussianGraph = graph.linearize(
      values);
  Matrix GraphInformation = GaussianGraph->hessian().first;

  // Check Hessian
  EXPECT(assert_equal(GraphInformation, CumulativeInformation, 1e-8));

  Matrix AugInformationMatrix = hessianFactor1->augmentedInformation()
      + hessianFactor2->augmentedInformation()
      + hessianFactor3->augmentedInformation();

  // Check Information vector
  Vector InfoVector = AugInformationMatrix.block(0, 18, 18, 1); // 18x18 Hessian + information vector

  // Check Hessian
  EXPECT(assert_equal(InfoVector, GaussianGraph->hessian().second, 1e-8));
}
//
///* *************************************************************************/
//TEST( SmartStereoProjectionPoseFactor, 3poses_2land_rotation_only_smart_projection_factor ){
//
//  KeyVector views;
//  views.push_back(x1);
//  views.push_back(x2);
//  views.push_back(x3);
//
//  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
//  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), Point3(0,0,1));
//  StereoCamera cam1(pose1, K2);
//
//  // create second camera 1 meter to the right of first camera
//  Pose3 pose2 = pose1 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0,0,0));
//  StereoCamera cam2(pose2, K2);
//
//  // create third camera 1 meter above the first camera
//  Pose3 pose3 = pose2 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0,0,0));
//  StereoCamera cam3(pose3, K2);
//
//  // three landmarks ~5 meters infront of camera
//  Point3 landmark1(5, 0.5, 1.2);
//  Point3 landmark2(5, -0.5, 1.2);
//
//  vector<StereoPoint2> measurements_cam1, measurements_cam2, measurements_cam3;
//
//  // 1. Project three landmarks into three cameras and triangulate
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark1, measurements_cam1);
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark2, measurements_cam2);
//
//  double rankTol = 50;
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(rankTol, linThreshold, manageDegeneracy));
//  smartFactor1->add(measurements_cam1, views, model, K2);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(rankTol, linThreshold, manageDegeneracy));
//  smartFactor2->add(measurements_cam2, views, model, K2);
//
//  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);
//  const SharedDiagonal noisePriorTranslation = noiseModel::Isotropic::Sigma(3, 0.10);
//  Point3 positionPrior = Point3(0,0,1);
//
//  NonlinearFactorGraph graph;
//  graph.push_back(smartFactor1);
//  graph.push_back(smartFactor2);
//  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
//  graph.push_back(PoseTranslationPrior<Pose3>(x2, positionPrior, noisePriorTranslation));
//  graph.push_back(PoseTranslationPrior<Pose3>(x3, positionPrior, noisePriorTranslation));
//
//  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.1,0.1,0.1)); // smaller noise
//  Values values;
//  values.insert(x1, pose1);
//  values.insert(x2, pose2*noise_pose);
//  // initialize third pose with some noise, we expect it to move back to original pose3
//  values.insert(x3, pose3*noise_pose*noise_pose);
//
//  Values result;
//  gttic_(SmartStereoProjectionPoseFactor);
//  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
//  result = optimizer.optimize();
//  gttoc_(SmartStereoProjectionPoseFactor);
//  tictoc_finishedIteration_();
//
//  // result.print("results of 3 camera, 3 landmark optimization \n");
//  // EXPECT(assert_equal(pose3,result.at<Pose3>(x3)));
//}
//
///* *************************************************************************/
//TEST( SmartStereoProjectionPoseFactor, 3poses_rotation_only_smart_projection_factor ){
//
//  KeyVector views;
//  views.push_back(x1);
//  views.push_back(x2);
//  views.push_back(x3);
//
//  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
//  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), Point3(0,0,1));
//  StereoCamera cam1(pose1, K);
//
//  // create second camera 1 meter to the right of first camera
//  Pose3 pose2 = pose1 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0,0,0));
//  StereoCamera cam2(pose2, K);
//
//  // create third camera 1 meter above the first camera
//  Pose3 pose3 = pose2 * Pose3(Rot3::RzRyRx(-0.05, 0.0, -0.05), Point3(0,0,0));
//  StereoCamera cam3(pose3, K);
//
//  // three landmarks ~5 meters infront of camera
//  Point3 landmark1(5, 0.5, 1.2);
//  Point3 landmark2(5, -0.5, 1.2);
//  Point3 landmark3(3, 0, 3.0);
//
//  vector<StereoPoint2> measurements_cam1, measurements_cam2, measurements_cam3;
//
//  // 1. Project three landmarks into three cameras and triangulate
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark1, measurements_cam1);
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark2, measurements_cam2);
//  stereo_projectToMultipleCameras(cam1, cam2, cam3, landmark3, measurements_cam3);
//
//  double rankTol = 10;
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor(rankTol, linThreshold, manageDegeneracy));
//  smartFactor1->add(measurements_cam1, views, model, K);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor2(new SmartStereoProjectionPoseFactor(rankTol, linThreshold, manageDegeneracy));
//  smartFactor2->add(measurements_cam2, views, model, K);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor3(new SmartStereoProjectionPoseFactor(rankTol, linThreshold, manageDegeneracy));
//  smartFactor3->add(measurements_cam3, views, model, K);
//
//  const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);
//  const SharedDiagonal noisePriorTranslation = noiseModel::Isotropic::Sigma(3, 0.10);
//  Point3 positionPrior = Point3(0,0,1);
//
//  NonlinearFactorGraph graph;
//  graph.push_back(smartFactor1);
//  graph.push_back(smartFactor2);
//  graph.push_back(smartFactor3);
//  graph.push_back(PriorFactor<Pose3>(x1, pose1, noisePrior));
//  graph.push_back(PoseTranslationPrior<Pose3>(x2, positionPrior, noisePriorTranslation));
//  graph.push_back(PoseTranslationPrior<Pose3>(x3, positionPrior, noisePriorTranslation));
//
//  //  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3)); // noise from regular projection factor test below
//  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/100, 0., -M_PI/100), Point3(0.1,0.1,0.1)); // smaller noise
//  Values values;
//  values.insert(x1, pose1);
//  values.insert(x2, pose2);
//  // initialize third pose with some noise, we expect it to move back to original pose3
//  values.insert(x3, pose3*noise_pose);
//
//  Values result;
//  gttic_(SmartStereoProjectionPoseFactor);
//  LevenbergMarquardtOptimizer optimizer(graph, values, lm_params);
//  result = optimizer.optimize();
//  gttoc_(SmartStereoProjectionPoseFactor);
//  tictoc_finishedIteration_();
//
//  // result.print("results of 3 camera, 3 landmark optimization \n");
//  // EXPECT(assert_equal(pose3,result.at<Pose3>(x3)));
//}
//
///* *************************************************************************/
//TEST( SmartStereoProjectionPoseFactor, Hessian ){
//
//  KeyVector views;
//  views.push_back(x1);
//  views.push_back(x2);
//
//  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
//  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI/2, 0., -M_PI/2), Point3(0,0,1));
//  StereoCamera cam1(pose1, K2);
//
//  // create second camera 1 meter to the right of first camera
//  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1,0,0));
//  StereoCamera cam2(pose2, K2);
//
//  // three landmarks ~5 meters infront of camera
//  Point3 landmark1(5, 0.5, 1.2);
//
//  // 1. Project three landmarks into three cameras and triangulate
//  StereoPoint2 cam1_uv1 = cam1.project(landmark1);
//  StereoPoint2 cam2_uv1 = cam2.project(landmark1);
//  vector<StereoPoint2> measurements_cam1;
//  measurements_cam1.push_back(cam1_uv1);
//  measurements_cam1.push_back(cam2_uv1);
//
//  SmartStereoProjectionPoseFactor::shared_ptr smartFactor1(new SmartStereoProjectionPoseFactor());
//  smartFactor1->add(measurements_cam1,views, model, K2);
//
//  Pose3 noise_pose = Pose3(Rot3::Ypr(-M_PI/10, 0., -M_PI/10), Point3(0.5,0.1,0.3));
//  Values values;
//  values.insert(x1, pose1);
//  values.insert(x2, pose2);
//
//  std::shared_ptr<GaussianFactor> hessianFactor = smartFactor1->linearize(values);
//
//  // compute triangulation from linearization point
//  // compute reprojection errors (sum squared)
//  // compare with hessianFactor.info(): the bottom right element is the squared sum of the reprojection errors (normalized by the covariance)
//  // check that it is correctly scaled when using noiseProjection = [1/4  0; 0 1/4]
//}
//

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, HessianWithRotation ) {
  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K);

  // create second camera 1 meter to the right of first camera
  Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
  StereoCamera cam2(pose2, K);

  // create third camera 1 meter above the first camera
  Pose3 pose3 = pose1 * Pose3(Rot3(), Point3(0, -1, 0));
  StereoCamera cam3(pose3, K);

  Point3 landmark1(5, 0.5, 1.2);

  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactorInstance(new SmartStereoProjectionPoseFactor(model));
  smartFactorInstance->add(measurements_cam1, views, K);

  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3);

  std::shared_ptr<GaussianFactor> hessianFactor =
      smartFactorInstance->linearize(values);
  // hessianFactor->print("Hessian factor \n");

  Pose3 poseDrift = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 0));

  Values rotValues;
  rotValues.insert(x1, poseDrift.compose(pose1));
  rotValues.insert(x2, poseDrift.compose(pose2));
  rotValues.insert(x3, poseDrift.compose(pose3));

  std::shared_ptr<GaussianFactor> hessianFactorRot =
      smartFactorInstance->linearize(rotValues);
  // hessianFactorRot->print("Hessian factor \n");

  // Hessian is invariant to rotations in the nondegenerate case
  EXPECT(
      assert_equal(hessianFactor->information(),
          hessianFactorRot->information(), 1e-7));

  Pose3 poseDrift2 = Pose3(Rot3::Ypr(-M_PI / 2, -M_PI / 3, -M_PI / 2),
      Point3(10, -4, 5));

  Values tranValues;
  tranValues.insert(x1, poseDrift2.compose(pose1));
  tranValues.insert(x2, poseDrift2.compose(pose2));
  tranValues.insert(x3, poseDrift2.compose(pose3));

  std::shared_ptr<GaussianFactor> hessianFactorRotTran =
      smartFactorInstance->linearize(tranValues);

  // Hessian is invariant to rotations and translations in the nondegenerate case
  EXPECT(
      assert_equal(hessianFactor->information(),
          hessianFactorRotTran->information(), 1e-6));
}

/* *************************************************************************/
TEST( SmartStereoProjectionPoseFactor, HessianWithRotationNonDegenerate ) {

  KeyVector views;
  views.push_back(x1);
  views.push_back(x2);
  views.push_back(x3);

  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
  Pose3 pose1 = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
  StereoCamera cam1(pose1, K2);

  // Second and third cameras in same place, which is a degenerate configuration
  Pose3 pose2 = pose1;
  Pose3 pose3 = pose1;
  StereoCamera cam2(pose2, K2);
  StereoCamera cam3(pose3, K2);

  Point3 landmark1(5, 0.5, 1.2);

  vector<StereoPoint2> measurements_cam1 = stereo_projectToMultipleCameras(cam1,
      cam2, cam3, landmark1);

  SmartStereoProjectionPoseFactor::shared_ptr smartFactor(new SmartStereoProjectionPoseFactor(model));
  smartFactor->add(measurements_cam1, views, K2);

  Values values;
  values.insert(x1, pose1);
  values.insert(x2, pose2);
  values.insert(x3, pose3);

  std::shared_ptr<GaussianFactor> hessianFactor = smartFactor->linearize(
      values);

  // check that it is non degenerate
  EXPECT(smartFactor->isValid());

  Pose3 poseDrift = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 0));

  Values rotValues;
  rotValues.insert(x1, poseDrift.compose(pose1));
  rotValues.insert(x2, poseDrift.compose(pose2));
  rotValues.insert(x3, poseDrift.compose(pose3));

  std::shared_ptr<GaussianFactor> hessianFactorRot = smartFactor->linearize(
      rotValues);

  // check that it is non degenerate
  EXPECT(smartFactor->isValid());

  // Hessian is invariant to rotations in the nondegenerate case
  EXPECT(
      assert_equal(hessianFactor->information(),
          hessianFactorRot->information(), 1e-6));

  Pose3 poseDrift2 = Pose3(Rot3::Ypr(-M_PI / 2, -M_PI / 3, -M_PI / 2),
      Point3(10, -4, 5));

  Values tranValues;
  tranValues.insert(x1, poseDrift2.compose(pose1));
  tranValues.insert(x2, poseDrift2.compose(pose2));
  tranValues.insert(x3, poseDrift2.compose(pose3));

  std::shared_ptr<GaussianFactor> hessianFactorRotTran =
      smartFactor->linearize(tranValues);

  // Hessian is invariant to rotations and translations in the degenerate case
  EXPECT(
      assert_equal(hessianFactor->information(),
#ifdef GTSAM_USE_EIGEN_MKL
          hessianFactorRotTran->information(), 1e-5));
#else
          hessianFactorRotTran->information(), 1e-6));
#endif
}

/* ************************************************************************* */
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */


/*
 * Copyright 2015 David A. Boyuka II
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * test-bitmap-bitcount.cpp
 *
 *  Created on: Jan 26, 2015
 *      Author: David A. Boyuka II
 */

#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <vector>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>

#include "pique/region/bitmap/bitmap.hpp"

static const uint64_t BIT_RANDOM_BITMAP_SIZE = (1ULL<<12) + 43;
static const double BIG_RANDOM_BITMAP_PROB = 0.1;

uint64_t make_random_bitmap(uint64_t nbits, double prob, std::vector< uint64_t > &bitvec) {
	uint64_t count = 0;
	boost::dynamic_bitset< uint64_t > bits(nbits, 0);

	for (uint64_t i = 0; i < nbits; i++) {
		const bool set = ((double)rand() / RAND_MAX) < prob;
		count += (set ? 1 : 0);
		bits[i] = set;
	}

	bitvec.resize(bits.num_blocks());
	boost::to_block_range(bits, bitvec.begin());
	return count;
}

int main(int argc, char **argv) {
	//                                     32 bits set        32 bits set        32 bits set         16 bits set
	std::vector< uint64_t > small_bitmap { 0x123456789ABCDEF, 0xFEDCBA987654321, 0x5A5A5A5A5A5A5A5A, 0x8421842184218421 };

	BitmapRegionEncoding small_aligned_bitmap(256, small_bitmap);
	assert(small_aligned_bitmap.get_element_count() == 32 + 32 + 32 + 16);

	BitmapRegionEncoding small_unaligned_bitmap(256 - 11, small_bitmap);
	assert(small_unaligned_bitmap.get_element_count() == 32 + 32 + 32 + 13); // 13 because the highest 3 set bits aren't counted due to the lower nbits

	std::vector< uint64_t > big_random;
	const uint64_t expected_big_random_count = make_random_bitmap(BIT_RANDOM_BITMAP_SIZE, BIG_RANDOM_BITMAP_PROB, big_random);

	// expected_big_random_count set
	BitmapRegionEncoding big_bitmap(BIT_RANDOM_BITMAP_SIZE, big_random);
	assert(big_bitmap.get_element_count() == expected_big_random_count);
}


<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      Ganeff, M.I. Solar radiation pressure benchmark data script,
 *          solarRadiationPressureBenchmarkData.m, available at http://tudat.tudelft.nl, 2012.
 *      Giancoli, D.C. Physics for Scientists and Engineers with Modern Physics
 *          Fourth Edition. New Jersey: Prentice-Hall, Inc., 1985.
 *      Hirsh, S.M. Solar radiation pressure benchmark data script,
 *          solarRadiationUnitTests.cpp, available at
 *          https://github.com/sethhirsh/solarRadiationUnitTests, 2013.
 *      Irizarry, V. The effect of solar radiation pressure on Ulysses orbit,
 *          http://ccar.colorado.edu/asen5050/projects/projects_2001/aponte/Ulysses.htm, 2001,
 *          last accessed: 7th October, 2013.
 *      Willmott, P. General Astrodynamics Library, http://www.amsat-bda.org/GAL_Downloads.html,
 *          2011, last accessed: 7th October, 2013.
 *
 */

#define BOOST_TEST_MAIN

#include <cmath>
#include <limits>

#include <boost/make_shared.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>

#include <Eigen/Core>

#include "Tudat/Basics/testMacros.h"

#include "Tudat/Astrodynamics/ElectroMagnetism/cannonBallRadiationPressureForce.h"
#include "Tudat/Astrodynamics/ElectroMagnetism/cannonBallRadiationPressureAcceleration.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_radiation_pressure_acceleration_and_force_models )

// Set radiation pressure at 1 AU [N/m^2].
const double radiationPressureAtOneAU = 4.56e-6;

// Set 1 AU in metres [m].
const double astronomicalUnitInMeters = 1.49598e11;

//! Test implementation of radiation force model.
BOOST_AUTO_TEST_CASE( testRadiationPressureForceModelGaneffData )
{
    // Benchmark data is obtained from MATLAB script (Ganeff, 2012).

    // Set expected radiation pressure force [N].
    const Eigen::Vector3d expectedRadiationPressureForce =
            Eigen::Vector3d( -0.975383093968723e-6, -0.975383093968723e-6, 0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.21;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 0.5;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( astronomicalUnitInMeters, astronomicalUnitInMeters, 0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Compute radiation pressure force [N].
    const Eigen::Vector3d computedRadiationPressureForce
                = electro_magnetism::computeCannonBallRadiationPressureForce(
                    radiationPressureAtTarget, positionVectorToSource,
                    areaSubjectToRadiationPressure, radiationPressureCoefficient );

    // Compare computed and expected radiation pressure force vectors.
    BOOST_CHECK_EQUAL( computedRadiationPressureForce.z( ),
                       expectedRadiationPressureForce.z( ) );

    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce.segment( 0, 2 ),
                                       expectedRadiationPressureForce.segment( 0, 2 ),
                                       1.0e-15 );
}

//! Test acceleration model on sample satellite at approximately 1 AU away from the Sun.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelEarth )
{

    // Benchmark data is obtained using the General Astrodynamics Library (Willmott, 2011).

    // Set expected radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d expectedRadiationPressureAcceleration =
            Eigen::Vector3d( -2.964e-06, 0.0, 0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.3;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 2.0;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Set mass of accelerated body [kg].
    const double mass = 4.0;

    // Compute radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d computedRadiationPressureAcceleration
            = electro_magnetism::computeCannonBallRadiationPressureAcceleration(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );

    // Compare computed and expected radiation pressure acceleration vectors
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration,
                                       expectedRadiationPressureAcceleration,
                                       1.0e-15 );
}

//! Test acceleration model on sample satellite at approximately the position of Venus with respect
//! to the Sun.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelVenus )
{
    // Benchmark data is obtained using the General Astrodynamics Library (Willmott, 2011).
    // Tests satellite at approximately the distance of Venus away from the Sun.

    // Set the distance from the Sun to Venus.
    const double distanceSunToVenus = 0.732 * astronomicalUnitInMeters;

    // Set expected radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d expectedRadiationPressureAcceleration =
            Eigen::Vector3d( -2.05147517201883e-05,
                             -2.05147517201883e-05,
                             0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.5;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 0.005;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( distanceSunToVenus / std::sqrt( 2.0 ),
                               distanceSunToVenus / std::sqrt( 2.0 ),
                               0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Set mass of accelerated body [kg].
    const double mass = 0.0022;

    // Compute radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d computedRadiationPressureAcceleration
            = electro_magnetism::computeCannonBallRadiationPressureAcceleration(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );

    // Compare computed and expected radiation pressure acceleration vectors.
    BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
                       std::numeric_limits< double >::min( ) );

    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration.segment( 0, 2 ),
                                       expectedRadiationPressureAcceleration.segment( 0, 2 ),
                                       1.0e-14 );
}

//! Test force model on sample planet at approximately the position of Uranus with respect to the
//! Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelUranus )
{
    // Benchmark data is obtained using the General Astrodynamics Library (Willmott, 2011).
    // Tests satellite at approximately the distance of Uranus away from the Sun.

    // Set expected radiation pressure force [N].
    const Eigen::Vector3d expectedRadiationPressureForce =
            Eigen::Vector3d( -4470411.61112176,
                             -4470411.61112176,
                             0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.8;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 69939064094327.4;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( 9.529 * astronomicalUnitInMeters / std::sqrt( 2.0 ),
                               9.529 * astronomicalUnitInMeters / std::sqrt( 2.0 ),
                               0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Compute radiation pressure force [N].
    const Eigen::Vector3d computedRadiationPressureForce
            = electro_magnetism::computeCannonBallRadiationPressureForce(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient );

    // Compare computed and expected radiation pressure force vectors.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce,
                                       expectedRadiationPressureForce,
                                       1.0e-14 );
}

//! Test force model on random satellite at a random distance with respect to the
//! Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelRandom )
{
    // Benchmark data is obtained using the General Astrodynamics Library (Willmott, 2011).
    // Tests satellite at random distance from the Sun.

    // Set expected radiation pressure force [N].
    const Eigen::Vector3d expectedRadiationPressureForce =
            Eigen::Vector3d( -3043733.21422537,
                             -2929936.30441141,
                             -473166.433773283 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.4058;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 514701.9505;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( 94359740.25,
                               90831886.1,
                               14668782.92 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Compute radiation pressure force [N].
    const Eigen::Vector3d computedRadiationPressureForce
            = electro_magnetism::computeCannonBallRadiationPressureForce(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient );

    // Compare computed and expected radiation pressure force vectors.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce,
                                       expectedRadiationPressureForce,
                                       1.0e-14 );
}

//! Test radiation force model on a hand at approximately 1 AU from the Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelGiancoliData )
{
    // Benchmark data is obtained from Physics for Scientists and Engineers
    // with Modern Physics Volume 2 (Ch. 31, Ex. 7) (Giancoli, 1985).

    // Set expected radiation pressure force [N].
    const Eigen::Vector3d expectedRadiationPressureForce =
            Eigen::Vector3d( 6.0e-8, 0.0, 0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.0;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 0.02;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Compute radiation pressure force [N].
    const Eigen::Vector3d computedRadiationPressureForce
            = electro_magnetism::computeCannonBallRadiationPressureForce(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient );

    // Compare computed and expected radiation pressure force vectors.
    BOOST_CHECK_SMALL( std::fabs( computedRadiationPressureForce.x( )
                                  - expectedRadiationPressureForce.x( ) ),
                       1.0e-6 );
    BOOST_CHECK_SMALL( computedRadiationPressureForce.y( ),
                       std::numeric_limits< double >::min( ) );
    BOOST_CHECK_SMALL( computedRadiationPressureForce.z( ),
                       std::numeric_limits< double >::min( ) );
}

//! Test radiation acceleration model on Ulysses satellite at 1AU.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelUlysses )
{
    // Benchmark data obtained from (Irizarry, 2001).

    // Set expected radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d expectedRadiationPressureAcceleration
        = Eigen::Vector3d( -1.713e-7, 0.0, 0.0 );

    // Set radiation pressure coefficient (1 + emissivity).
    const double radiationPressureCoefficient = 1.0 + 0.327;

    // Set area on target that is subject to radiation pressure [m^2].
    const double areaSubjectToRadiationPressure = 10.59;

    // Set position vector [m].
    Eigen::Vector3d positionVectorToSource
            = Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );

    // Set radiation pressure at target [N/m^2].
    const double radiationPressureAtTarget = radiationPressureAtOneAU
            * astronomicalUnitInMeters * astronomicalUnitInMeters
            / positionVectorToSource.squaredNorm( );

    // Normalize position vector to get vector pointing to source in non-dimensional units.
    positionVectorToSource.normalize( );

    // Set mass of accelerated body [kg].
    const double mass = 370.0;

    // Compute radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d computedRadiationPressureAcceleration
            = electro_magnetism::computeCannonBallRadiationPressureAcceleration(
                radiationPressureAtTarget, positionVectorToSource,
                areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );

    // Compare computed and expected radiation pressure acceleration vectors.
    BOOST_CHECK_SMALL( std::fabs( computedRadiationPressureAcceleration.x( )
                                  - expectedRadiationPressureAcceleration.x( ) ),
                       1.0e-8 );
    BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.y( ),
                       std::numeric_limits< double >::min( ) );
    BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
                       std::numeric_limits< double >::min( ) );
}

//! Test class implementation of radiation pressure acceleration model.

// Set position of source of radiation pressure at origin [m].
static Eigen::Vector3d sourcePosition = Eigen::Vector3d::Zero( );

// Get position of source of radiation pressure [m].
Eigen::Vector3d getSourcePosition( ) { return sourcePosition; }

// Set position of accelerated body [m].
static Eigen::Vector3d acceleratedBodyPosition
    = Eigen::Vector3d( -astronomicalUnitInMeters, 0.0, 0.0 );

// Get position of accelerated body [m].
Eigen::Vector3d getAcceleratedBodyPosition( ) { return acceleratedBodyPosition; }

// Get vector from accelerated body to source [m].
Eigen::Vector3d getVectorToSource( )
{
    return getSourcePosition( ) - getAcceleratedBodyPosition( );
}

// Set radiation pressure at location of acceleration body [N/m^2].
static double radiationPressure = radiationPressureAtOneAU
    * astronomicalUnitInMeters * astronomicalUnitInMeters / getVectorToSource( ).squaredNorm( );

// Get radiation pressure at location of acceleration body [N/m^2].
double getRadiationPressure( ) { return radiationPressure; }

// Set radiation pressure coefficient.
static double radiationPressureCoefficient = 1.0 + 0.3;

// Get radiation pressure coefficient.
double getRadiationPressureCoefficient( ) { return radiationPressureCoefficient; }

// Set area subject to radiation pressure [m^2].
static double areaSubjectToRadiationPressure = 2.0;

// Get area subject to radiation pressure [m^2].
double getAreaSubjectToRadiationPressure( ) { return areaSubjectToRadiationPressure; }

// Set mass of accelerated body [kg].
static double massOfAcceleratedBody = 4.0;

// Get mass of acceleration body [kg].
double getMassOfAcceleratedBody( ) { return massOfAcceleratedBody; }

//! Test radiation pressure acceleration model constructor.
BOOST_AUTO_TEST_CASE( testRadiationPressureAccelerationModelClassConstructor )
{
    // Declare and initialize cannon-ball radiation pressure acceleration model.
    electro_magnetism::CannonBallRadiationPressurePointer radiationPressureModel
        = std::make_shared< electro_magnetism::CannonBallRadiationPressureAcceleration >(
            &getSourcePosition, &getAcceleratedBodyPosition, &getRadiationPressure,
            &getRadiationPressureCoefficient, &getAreaSubjectToRadiationPressure,
            &getMassOfAcceleratedBody );

    // Set expected radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d expectedRadiationPressureAcceleration
        = Eigen::Vector3d( -2.964e-06, 0.0, 0.0 );

    // Compute radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d computedRadiationPressureAcceleration
        = radiationPressureModel->getAcceleration( );

    // Compare computed and expected radiation pressure acceleration vectors.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration,
                                       expectedRadiationPressureAcceleration,
                                       1.0e-15 );
}

//! Test radiation pressure acceleration model update-members function.
BOOST_AUTO_TEST_CASE( testRadiationPressureAccelerationModelClassUpdateMembers )
{
    // Declare and initialize cannon-ball radiation pressure acceleration model.
    electro_magnetism::CannonBallRadiationPressurePointer radiationPressureModel
        = std::make_shared< electro_magnetism::CannonBallRadiationPressureAcceleration >(
            &getSourcePosition, &getAcceleratedBodyPosition, &getRadiationPressure,
            &getRadiationPressureCoefficient, &getAreaSubjectToRadiationPressure,
            &getMassOfAcceleratedBody );

    // Set expected radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d expectedRadiationPressureAcceleration
        = Eigen::Vector3d( -2.05147517201883e-05,
                           -2.05147517201883e-05,
                           0.0 );

    // Set the distance from the Sun to Venus [m].
    const double distanceSunToVenus = 0.732 * astronomicalUnitInMeters;

    // Update position of accelerated body [m].
    acceleratedBodyPosition = Eigen::Vector3d( -distanceSunToVenus / std::sqrt( 2.0 ),
                                               -distanceSunToVenus / std::sqrt( 2.0 ),
                                               0.0 );

    // Update radiation pressure at location of accelerated body [N/m^2].
    radiationPressure = radiationPressureAtOneAU
        * astronomicalUnitInMeters * astronomicalUnitInMeters
        / getVectorToSource( ).squaredNorm( );

    // Update radiation pressure coefficient.
    radiationPressureCoefficient = 1.0 + 0.5;

    // Update area subject to radiation pressure [m^2].
    areaSubjectToRadiationPressure = 0.005;

    // Update mass of accelerated body [kg].
    massOfAcceleratedBody = 0.0022;

    // Update class members.
    radiationPressureModel->updateMembers( );

    // Compute radiation pressure acceleration [m/s^2].
    const Eigen::Vector3d computedRadiationPressureAcceleration
        = radiationPressureModel->getAcceleration( );

    // Compare computed and expected radiation pressure acceleration vectors.
    BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
                       std::numeric_limits< double >::min( ) );

    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration.segment( 0, 2 ),
                                       expectedRadiationPressureAcceleration.segment( 0, 2 ),
                                       1.0e-14 );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat


/*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.

This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org

ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License.  You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>

This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file qle/termstructures/dynamiccpivolatilitystructure.hpp
\brief dynamic zero inflation volatility structure
\ingroup termstructures
*/

#pragma once

#include <boost/make_shared.hpp>
#include <ql/termstructures/volatility/inflation/cpivolatilitystructure.hpp>
#include <ql/termstructures/volatility/smilesection.hpp>
#include <qle/termstructures/dynamicstype.hpp>
#include <qle/termstructures/interpolatedcpivolatilitysurface.hpp>

namespace QuantExt {
using namespace QuantLib;

//! Converts a CPIVolatilityStructure with fixed reference date into a floating reference date term structure.
/*! Different ways of reacting to time decay can be specified.

\ingroup termstructures
*/

class DynamicCPIVolatilitySurface : public CPIVolatilitySurface {
public:
    DynamicCPIVolatilitySurface(const boost::shared_ptr<CPIVolatilitySurface>& source,
                                ReactionToTimeDecay decayMode = ConstantVariance);

protected:
    //! \name CPIVolatilitySurface interface
    //@{
    Volatility volatilityImpl(Time length, Rate strike) const;
    //@}

    //! \name VolatilityTermStructure interface
    //@{
    Rate minStrike() const;
    Rate maxStrike() const;
    //@}

    //! \name VolatilityTermStructure interface
    //@{
    Date maxDate() const;
    //@}

    //! \name Observer interface
    //@{
    void update();
    //@}

private:
    const boost::shared_ptr<CPIVolatilitySurface> source_;
    ReactionToTimeDecay decayMode_;
    const Date originalReferenceDate_;
};

} // namespace QuantExt


/*
auther: wanyouwen
date: 2018.6.24

双目示例:
双目相机app程序框架：

1. 读取相机配置文件(内参数 畸变矫正参数 双目对齐变换矩阵) =======================
   cv::FileStorage fsSettings(setting_filename, cv::FileStorage::READ);
   fsSettings["LEFT.K"] >> K_l;//内参数
   fsSettings["LEFT.D"] >> D_l;// 畸变矫正
   fsSettings["LEFT.P"] >> P_l;// P_l,P_r --左右相机在校准后坐标系中的投影矩阵 3×4
   fsSettings["LEFT.R"] >> R_l;// R_l,R_r --左右相机校准变换（旋转）矩阵  3×3
2. 计算双目矫正映射矩阵========================================================
   cv::Mat M1l,M2l,M1r,M2r;
       cv::initUndistortRectifyMap(K_l,D_l,R_l,P_l.rowRange(0,3).colRange(0,3),cv::Size(cols_l,rows_l),CV_32F,M1l,M2l);
       cv::initUndistortRectifyMap(K_r,D_r,R_r,P_r.rowRange(0,3).colRange(0,3),cv::Size(cols_r,rows_r),CV_32F,M1r,M2r);
3. 创建双目系统===============================================================
   ORB_SLAM2::System SLAM(vocabulary_filepath, setting_filename, ORB_SLAM2::System::STEREO, true);
4. 从双目设备捕获图像,设置分辨率捕获图像========================================
   cv::VideoCapture CapAll(deviceid); //打开相机设备
   //设置分辨率   1280*480  分成两张 640*480  × 2 左右相机
       CapAll.set(CV_CAP_PROP_FRAME_WIDTH,1280);
       CapAll.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
    5. 获取左右相机图像===========================================================
   CapAll.read(src_img);
   imLeft  = src_img(cv::Range(0, 480), cv::Range(0, 640));
       imRight = src_img(cv::Range(0, 480), cv::Range(640, 1280));
6. 使用2步获取的双目矫正映射矩阵 矫正 左右相机图像==============================
   cv::remap(imLeft,imLeftRect,M1l,M2l,cv::INTER_LINEAR);
       cv::remap(imRight,imRightRect,M1r,M2r,cv::INTER_LINEAR);
7. 记录时间戳 time ，并计时===================================================
	#ifdef COMPILEDWITHC11
	   std::chrono::steady_clock::time_point    t1 = std::chrono::steady_clock::now();
	#else
	   std::chrono::monotonic_clock::time_point t1 = std::chrono::monotonic_clock::now();
	#endif
    8. 把左右图像和时间戳 传给 SLAM系统===========================================
    SLAM.TrackStereo(imLeftRect, imRightRect, time);
9. 计时结束，计算时间差，处理时间=============================================
10.循环执行 5-9步===========================================================
11.结束，关闭slam系统，关闭所有线程===========================================
12.保存相机轨迹==============================================================

*/
#include<iostream>
#include<algorithm>
#include<fstream>
#include<iomanip>
#include<chrono>//chrono是一个time library, 源于boost，现在已经是C++标准。

#include<opencv2/core/core.hpp>
#include<System.h>

using namespace std;
using namespace cv;

#include <boost/format.hpp>  // 格式化字符串 for formating strings 处理图像文件格式
#include <boost/thread/thread.hpp>

static void print_help()
{
    printf("\n orbslam2 stereo test : \n");//生成视差和点云图
    printf("\n Usage: my_stereo [-v=<path_to_vocabulary>] [-s=<path_to_settings>]\n"
           "\n [--d=<camera_id>] \n");
}

int main(int argc, char **argv)
{
    //std::uint32_t timestamp;
    double time=0.0, ttrack=0;

    //vector<IMUData> imudatas;
    std::string setting_filename = "";    //配置文件
    std::string vocabulary_filepath = ""; //关键帧数据库 词典 重定位
    int deviceid = 1;                     //相机设备id
    cv::CommandLineParser parser(argc, argv,
        "{help h||}{d|1|}{v|../../Vocabulary/ORBvoc.bin|}{s|my_stereo.yaml|}");
//=======打印帮助信息============
    if(parser.has("help"))
    {
        print_help();
        return 0;
    }
    if( parser.has("d") )
        deviceid = parser.get<int>("d");//相机设备id
    if( parser.has("s") )
        setting_filename = parser.get<std::string>("s");//
    if( parser.has("v") )
        vocabulary_filepath = parser.get<std::string>("v");//
    if (!parser.check()) {
        parser.printErrors();
        return 1;
    }
//if(setting_filename.empty())//{

 //1.  读取相机配置文件(内参数 畸变矫正参数 双目对齐变换矩阵 ) ====================
    cv::FileStorage fsSettings(setting_filename, cv::FileStorage::READ);
    if(!fsSettings.isOpened())
    {
        cerr << "ERROR: Wrong path to setting file : " << setting_filename << endl;
        return -1;
    }

    cv::Mat K_l, K_r, D_l, D_r, P_l, P_r, R_l, R_r;
    fsSettings["LEFT.K"] >> K_l;//内参数
    if(K_l.empty())  cout << "K_l missing "<<endl;
    fsSettings["RIGHT.K"] >> K_r;//
    if(K_r.empty()) cout << "K_r missing "<<endl;
    fsSettings["LEFT.D"] >> D_l;// 畸变矫正
    if(D_l.empty()) cout << "D_l missing "<<endl;
    fsSettings["RIGHT.D"] >> D_r;
    if(D_r.empty()) cout << "D_r missing "<<endl;

    fsSettings["LEFT.P"] >> P_l;// P_l,P_r --左右相机在校准后坐标系中的投影矩阵 3×4
    if(P_l.empty()) cout << "P_l missing "<<endl;
    fsSettings["RIGHT.P"] >> P_r;
    if(K_r.empty()) cout << "P_r missing "<<endl;

    fsSettings["LEFT.R"] >> R_l;// R_l,R_r --左右相机校准变换（旋转）矩阵  3×3
    if(R_l.empty()) cout << "R_l missing "<<endl;
    fsSettings["RIGHT.R"] >> R_r;
    if(R_r.empty()) cout << "R_r missing "<<endl;

    int rows_l = fsSettings["LEFT.height"];
    int cols_l = fsSettings["LEFT.width"];
    int rows_r = fsSettings["RIGHT.height"];
    int cols_r = fsSettings["RIGHT.width"];

    if(K_l.empty() || K_r.empty() || P_l.empty() || P_r.empty() || R_l.empty() || R_r.empty() || D_l.empty() || D_r.empty() || rows_l==0 || rows_r==0 || cols_l==0 || cols_r==0)
    {
        cerr << "ERROR: Calibration parameters to rectify stereo are missing!" << endl;
        return -1;
    }
//}

//外参数
// Mat R, T, R1, P1, R2, P2;
//fs["R"] >> R;
//fs["T"] >> T;
//图像矫正摆正 映射计算
//stereoRectify( K_l, D_l, K_r, D_r, cv::Size(cols_l,rows_l), R, T, R1, R2, P1, P2, Q, CALIB_ZERO_DISPARITY, -1, cv::Size(cols_l,rows_l), &roi1, &roi2 );

// 2. 计算双目矫正映射矩阵================================================
    cv::Mat M1l,M2l,M1r,M2r;
    cv::initUndistortRectifyMap(K_l,D_l,R_l,P_l.rowRange(0,3).colRange(0,3),cv::Size(cols_l,rows_l),CV_32F,M1l,M2l);
    cv::initUndistortRectifyMap(K_r,D_r,R_r,P_r.rowRange(0,3).colRange(0,3),cv::Size(cols_r,rows_r),CV_32F,M1r,M2r);

// 3. 创建双目系统 ORB_SLAM2::System======================================
    ORB_SLAM2::System SLAM(vocabulary_filepath, setting_filename, ORB_SLAM2::System::STEREO, true);

    cout << endl << "-------" << endl;
    cout << "Start processing sequence ..." << endl;
// 4. 从双目设备捕获图像设置分辨率捕获图像 ===================================================
    cv::VideoCapture CapAll(deviceid); //打开相机设备
    if( !CapAll.isOpened() )
    {
       printf("打开摄像头失败\r\n");
       printf("再试一次\r\n");
       //sleep(1);//延时1秒
       cv::VideoCapture CapAll(1); //打开相机设备
       if( !CapAll.isOpened() ) {
         printf("打开摄像头失败\r\n");
	 printf("再试一次..\r\n");
          //sleep(1);//延时1秒
          cv::VideoCapture CapAll(1); //打开相机设备
          if( !CapAll.isOpened() ) {
	  printf("打开摄像头失败\r\n");
	   return -1;
         }
       }
   }
    //设置分辨率   1280*480  分成两张 640*480  × 2 左右相机
    CapAll.set(CV_CAP_PROP_FRAME_WIDTH,1280);
    CapAll.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

    cv::Mat src_img, imLeft, imRight, imLeftRect, imRightRect;

    while(CapAll.read(src_img))
     {
// 5. 获取左右相机图像====================================================
        imLeft  = src_img(cv::Range(0, 480), cv::Range(0, 640));
        imRight = src_img(cv::Range(0, 480), cv::Range(640, 1280));

// 6. 矫正左右相机图像====================================================
        cv::remap(imLeft,imLeftRect,M1l,M2l,cv::INTER_LINEAR);
        cv::remap(imRight,imRightRect,M1r,M2r,cv::INTER_LINEAR);

// 7. 记录时间戳 tframe ，并计时==========================================
#ifdef COMPILEDWITHC11
        std::chrono::steady_clock::time_point        t1 = std::chrono::steady_clock::now();
#else
        std::chrono::monotonic_clock::time_point t1 = std::chrono::monotonic_clock::now();
#endif
        time += ttrack ;

// 8. 把左右图像和时间戳 传给 SLAM系统====================================
        SLAM.TrackStereo(imLeftRect, imRightRect, time);

// 9. 计时结束，计算时间差，处理时间======================================
#ifdef COMPILEDWITHC11
        std::chrono::steady_clock::time_point        t2 = std::chrono::steady_clock::now();
#else
        std::chrono::monotonic_clock::time_point t2 = std::chrono::monotonic_clock::now();
#endif

        ttrack= std::chrono::duration_cast<std::chrono::duration<double> >(t2 - t1).count();

  //  if(ttrack<T)
//   usleep((T-ttrack)*1e6); //sleep

    }

// 10. 结束，关闭slam系统，关闭所有线程===================================
    SLAM.Shutdown();
// 11. 保存相机轨迹======================================================
    SLAM.SaveTrajectoryKITTI("myCameraTrajectory.txt");

    CapAll.release();
    cv::destroyAllWindows();
    return 0;
}