text:
/* ----------------------------------------------------------------------------

 * 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 testExpressionFactor.cpp
 * @date September 18, 2014
 * @author Frank Dellaert
 * @author Paul Furgale
 * @brief unit tests for Block Automatic Differentiation
 */

#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/Testable.h>
#include <gtsam/nonlinear/ExpressionFactor.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/PriorFactor.h>
#include <gtsam/nonlinear/expressionTesting.h>
#include <gtsam/slam/GeneralSFMFactor.h>
#include <gtsam/slam/ProjectionFactor.h>
#include <gtsam/slam/expressions.h>

#include <boost/assign/list_of.hpp>
using boost::assign::list_of;
using namespace std::placeholders;

using namespace std;
using namespace gtsam;

Point2 measured(-17, 30);
SharedNoiseModel model = noiseModel::Unit::Create(2);

// This deals with the overload problem and makes the expressions factor
// understand that we work on Point3
Point2 (*Project)(const Point3&, OptionalJacobian<2, 3>) = &PinholeBase::Project;

namespace leaf {
// Create some values
struct MyValues: public Values {
  MyValues() {
    insert(2, Point2(3, 5));
  }
} values;

// Create leaf
Point2_ p(2);
}

/* ************************************************************************* */
// Leaf
TEST(ExpressionFactor, Leaf) {
  using namespace leaf;

  // Create old-style factor to create expected value and derivatives.
  PriorFactor<Point2> old(2, Point2(0, 0), model);

  // Create the equivalent factor with expression.
  ExpressionFactor<Point2> f(model, Point2(0, 0), p);

  // Check values and derivatives.
  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f.dim());
  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);
  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));
}

/* ************************************************************************* */
// Test leaf expression with noise model of different variance.
TEST(ExpressionFactor, Model) {
  using namespace leaf;

  SharedNoiseModel model = noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.01));

  // Create old-style factor to create expected value and derivatives.
  PriorFactor<Point2> old(2, Point2(0, 0), model);

  // Create the equivalent factor with expression.
  ExpressionFactor<Point2> f(model, Point2(0, 0), p);

  // Check values and derivatives.
  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f.dim());
  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);
  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));
  EXPECT_CORRECT_FACTOR_JACOBIANS(f, values, 1e-5, 1e-5); // another way
}

/* ************************************************************************* */
// Test leaf expression with constrained noise model.
TEST(ExpressionFactor, Constrained) {
  using namespace leaf;

  SharedDiagonal model = noiseModel::Constrained::MixedSigmas(Vector2(0.2, 0));

  // Create old-style factor to create expected value and derivatives
  PriorFactor<Point2> old(2, Point2(0, 0), model);

  // Concise version
  ExpressionFactor<Point2> f(model, Point2(0, 0), p);
  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f.dim());
  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);
  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));
}

/* ************************************************************************* */
// Unary(Leaf))
TEST(ExpressionFactor, Unary) {

  // Create some values
  Values values;
  values.insert(2, Point3(0, 0, 1));

  JacobianFactor expected( //
      2, (Matrix(2, 3) << 1, 0, 0, 0, 1, 0).finished(), //
      Vector2(-17, 30));

  // Create leaves
  Point3_ p(2);

  // Concise version
  ExpressionFactor<Point2> f(model, measured, project(p));
  EXPECT_LONGS_EQUAL(2, f.dim());
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  boost::shared_ptr<JacobianFactor> jf = //
      boost::dynamic_pointer_cast<JacobianFactor>(gf);
  EXPECT(assert_equal(expected, *jf, 1e-9));
}

/* ************************************************************************* */
// Unary(Leaf)) and Unary(Unary(Leaf)))
// wide version (not handled in fixed-size pipeline)
typedef Eigen::Matrix<double,9,3> Matrix93;
Vector9 wide(const Point3& p, OptionalJacobian<9,3> H) {
  Vector9 v;
  v << p, p, p;
  if (H) *H << I_3x3, I_3x3, I_3x3;
  return v;
}

typedef Eigen::Matrix<double,9,9> Matrix9;
Vector9 id9(const Vector9& v, OptionalJacobian<9,9> H) {
  if (H) *H = Matrix9::Identity();
  return v;
}

TEST(ExpressionFactor, Wide) {
  // Create some values
  Values values;
  values.insert(2, Point3(0, 0, 1));
  Point3_ point(2);
  Vector9 measured;
  measured.setZero();
  Expression<Vector9> expression(wide,point);
  SharedNoiseModel model = noiseModel::Unit::Create(9);

  ExpressionFactor<Vector9> f1(model, measured, expression);
  EXPECT_CORRECT_FACTOR_JACOBIANS(f1, values, 1e-5, 1e-9);

  Expression<Vector9> expression2(id9,expression);
  ExpressionFactor<Vector9> f2(model, measured, expression2);
  EXPECT_CORRECT_FACTOR_JACOBIANS(f2, values, 1e-5, 1e-9);
}

/* ************************************************************************* */
static Point2 myUncal(const Cal3_S2& K, const Point2& p,
    OptionalJacobian<2,5> Dcal, OptionalJacobian<2,2> Dp) {
  return K.uncalibrate(p, Dcal, Dp);
}

// Binary(Leaf,Leaf)
TEST(ExpressionFactor, Binary) {

  typedef internal::BinaryExpression<Point2, Cal3_S2, Point2> Binary;

  Cal3_S2_ K_(1);
  Point2_ p_(2);
  Binary binary(myUncal, K_, p_);

  // Create some values
  Values values;
  values.insert(1, Cal3_S2());
  values.insert(2, Point2(0, 0));

  // Check size
  size_t size = binary.traceSize();
  // Use Variable Length Array, allocated on stack by gcc
  // Note unclear for Clang: http://clang.llvm.org/compatibility.html#vla
  internal::ExecutionTraceStorage traceStorage[size];
  internal::ExecutionTrace<Point2> trace;
  Point2 value = binary.traceExecution(values, trace, traceStorage);
  EXPECT(assert_equal(Point2(0,0),value, 1e-9));
  // trace.print();

  // Expected Jacobians
  Matrix25 expected25;
  expected25 << 0, 0, 0, 1, 0, 0, 0, 0, 0, 1;
  Matrix2 expected22;
  expected22 << 1, 0, 0, 1;

  // Check matrices
  boost::optional<Binary::Record*> r = trace.record<Binary::Record>();
  CHECK(r);
  EXPECT(assert_equal(expected25, (Matrix ) (*r)->dTdA1, 1e-9));
  EXPECT(assert_equal(expected22, (Matrix ) (*r)->dTdA2, 1e-9));
}

/* ************************************************************************* */
// Unary(Binary(Leaf,Leaf))
TEST(ExpressionFactor, Shallow) {

  // Create some values
  Values values;
  values.insert(1, Pose3());
  values.insert(2, Point3(0, 0, 1));

  // Create old-style factor to create expected value and derivatives
  GenericProjectionFactor<Pose3, Point3> old(measured, model, 1, 2,
      boost::make_shared<Cal3_S2>());
  double expected_error = old.error(values);
  GaussianFactor::shared_ptr expected = old.linearize(values);

  // Create leaves
  Pose3_ x_(1);
  Point3_ p_(2);

  // Construct expression, concise evrsion
  Point2_ expression = project(transformTo(x_, p_));

  // Get and check keys and dims
  KeyVector keys;
  FastVector<int> dims;
  boost::tie(keys, dims) = expression.keysAndDims();
  LONGS_EQUAL(2,keys.size());
  LONGS_EQUAL(2,dims.size());
  LONGS_EQUAL(1,keys[0]);
  LONGS_EQUAL(2,keys[1]);
  LONGS_EQUAL(6,dims[0]);
  LONGS_EQUAL(3,dims[1]);

  // traceExecution of shallow tree
  typedef internal::UnaryExpression<Point2, Point3> Unary;
  size_t size = expression.traceSize();
  internal::ExecutionTraceStorage traceStorage[size];
  internal::ExecutionTrace<Point2> trace;
  Point2 value = expression.traceExecution(values, trace, traceStorage);
  EXPECT(assert_equal(Point2(0,0),value, 1e-9));
  // trace.print();

  // Expected Jacobians
  Matrix23 expected23;
  expected23 << 1, 0, 0, 0, 1, 0;

  // Check matrices
  boost::optional<Unary::Record*> r = trace.record<Unary::Record>();
  CHECK(r);
  EXPECT(assert_equal(expected23, (Matrix)(*r)->dTdA1, 1e-9));

  // Linearization
  ExpressionFactor<Point2> f2(model, measured, expression);
  EXPECT_DOUBLES_EQUAL(expected_error, f2.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f2.dim());
  boost::shared_ptr<GaussianFactor> gf2 = f2.linearize(values);
  EXPECT(assert_equal(*expected, *gf2, 1e-9));
}

/* ************************************************************************* */
// Binary(Leaf,Unary(Binary(Leaf,Leaf)))
TEST(ExpressionFactor, tree) {

  // Create some values
  Values values;
  values.insert(1, Pose3());
  values.insert(2, Point3(0, 0, 1));
  values.insert(3, Cal3_S2());

  // Create old-style factor to create expected value and derivatives
  GeneralSFMFactor2<Cal3_S2> old(measured, model, 1, 2, 3);
  double expected_error = old.error(values);
  GaussianFactor::shared_ptr expected = old.linearize(values);

  // Create leaves
  Pose3_ x(1);
  Point3_ p(2);
  Cal3_S2_ K(3);

  // Create expression tree
  Point3_ p_cam(x, &Pose3::transformTo, p);
  Point2_ xy_hat(Project, p_cam);
  Point2_ uv_hat(K, &Cal3_S2::uncalibrate, xy_hat);

  // Create factor and check value, dimension, linearization
  ExpressionFactor<Point2> f(model, measured, uv_hat);
  EXPECT_DOUBLES_EQUAL(expected_error, f.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f.dim());
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  EXPECT(assert_equal(*expected, *gf, 1e-9));

  // Concise version
  ExpressionFactor<Point2> f2(model, measured,
      uncalibrate(K, project(transformTo(x, p))));
  EXPECT_DOUBLES_EQUAL(expected_error, f2.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f2.dim());
  boost::shared_ptr<GaussianFactor> gf2 = f2.linearize(values);
  EXPECT(assert_equal(*expected, *gf2, 1e-9));

  // Try ternary version
  ExpressionFactor<Point2> f3(model, measured, project3(x, p, K));
  EXPECT_DOUBLES_EQUAL(expected_error, f3.error(values), 1e-9);
  EXPECT_LONGS_EQUAL(2, f3.dim());
  boost::shared_ptr<GaussianFactor> gf3 = f3.linearize(values);
  EXPECT(assert_equal(*expected, *gf3, 1e-9));
}

/* ************************************************************************* */
TEST(ExpressionFactor, Compose1) {

  // Create expression
  Rot3_ R1(1), R2(2);
  Rot3_ R3 = R1 * R2;

  // Create factor
  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);

  // Create some values
  Values values;
  values.insert(1, Rot3());
  values.insert(2, Rot3());

  // Check unwhitenedError
  std::vector<Matrix> H(2);
  Vector actual = f.unwhitenedError(values, H);
  EXPECT(assert_equal(I_3x3, H[0],1e-9));
  EXPECT(assert_equal(I_3x3, H[1],1e-9));

  // Check linearization
  JacobianFactor expected(1, I_3x3, 2, I_3x3, Z_3x1);
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  boost::shared_ptr<JacobianFactor> jf = //
      boost::dynamic_pointer_cast<JacobianFactor>(gf);
  EXPECT(assert_equal(expected, *jf,1e-9));
}

/* ************************************************************************* */
// Test compose with arguments referring to the same rotation
TEST(ExpressionFactor, compose2) {

  // Create expression
  Rot3_ R1(1), R2(1);
  Rot3_ R3 = R1 * R2;

  // Create factor
  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);

  // Create some values
  Values values;
  values.insert(1, Rot3());

  // Check unwhitenedError
  std::vector<Matrix> H(1);
  Vector actual = f.unwhitenedError(values, H);
  EXPECT_LONGS_EQUAL(1, H.size());
  EXPECT(assert_equal(2*I_3x3, H[0],1e-9));

  // Check linearization
  JacobianFactor expected(1, 2 * I_3x3, Z_3x1);
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  boost::shared_ptr<JacobianFactor> jf = //
      boost::dynamic_pointer_cast<JacobianFactor>(gf);
  EXPECT(assert_equal(expected, *jf,1e-9));
}

/* ************************************************************************* */
// Test compose with one arguments referring to a constant same rotation
TEST(ExpressionFactor, compose3) {

  // Create expression
  Rot3_ R1(Rot3::identity()), R2(3);
  Rot3_ R3 = R1 * R2;

  // Create factor
  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);

  // Create some values
  Values values;
  values.insert(3, Rot3());

  // Check unwhitenedError
  std::vector<Matrix> H(1);
  Vector actual = f.unwhitenedError(values, H);
  EXPECT_LONGS_EQUAL(1, H.size());
  EXPECT(assert_equal(I_3x3, H[0],1e-9));

  // Check linearization
  JacobianFactor expected(3, I_3x3, Z_3x1);
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  boost::shared_ptr<JacobianFactor> jf = //
      boost::dynamic_pointer_cast<JacobianFactor>(gf);
  EXPECT(assert_equal(expected, *jf,1e-9));
}

/* ************************************************************************* */
// Test compose with three arguments
Rot3 composeThree(const Rot3& R1, const Rot3& R2, const Rot3& R3,
    OptionalJacobian<3, 3> H1, OptionalJacobian<3, 3> H2, OptionalJacobian<3, 3> H3) {
  // return dummy derivatives (not correct, but that's ok for testing here)
  if (H1)
    *H1 = I_3x3;
  if (H2)
    *H2 = I_3x3;
  if (H3)
    *H3 = I_3x3;
  return R1 * (R2 * R3);
}

TEST(ExpressionFactor, composeTernary) {

  // Create expression
  Rot3_ A(1), B(2), C(3);
  Rot3_ ABC(composeThree, A, B, C);

  // Create factor
  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), ABC);

  // Create some values
  Values values;
  values.insert(1, Rot3());
  values.insert(2, Rot3());
  values.insert(3, Rot3());

  // Check unwhitenedError
  std::vector<Matrix> H(3);
  Vector actual = f.unwhitenedError(values, H);
  EXPECT_LONGS_EQUAL(3, H.size());
  EXPECT(assert_equal(I_3x3, H[0],1e-9));
  EXPECT(assert_equal(I_3x3, H[1],1e-9));
  EXPECT(assert_equal(I_3x3, H[2],1e-9));

  // Check linearization
  JacobianFactor expected(1, I_3x3, 2, I_3x3, 3, I_3x3, Z_3x1);
  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);
  boost::shared_ptr<JacobianFactor> jf = //
      boost::dynamic_pointer_cast<JacobianFactor>(gf);
  EXPECT(assert_equal(expected, *jf,1e-9));
}

TEST(ExpressionFactor, tree_finite_differences) {

  // Create some values
  Values values;
  values.insert(1, Pose3());
  values.insert(2, Point3(0, 0, 1));
  values.insert(3, Cal3_S2());

  // Create leaves
  Pose3_ x(1);
  Point3_ p(2);
  Cal3_S2_ K(3);

  // Create expression tree
  Point3_ p_cam(x, &Pose3::transformTo, p);
  Point2_ xy_hat(Project, p_cam);
  Point2_ uv_hat(K, &Cal3_S2::uncalibrate, xy_hat);

  const double fd_step = 1e-5;
  const double tolerance = 1e-5;
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(uv_hat, values, fd_step, tolerance);
}

TEST(ExpressionFactor, push_back) {
  NonlinearFactorGraph graph;
  graph.addExpressionFactor(model, Point2(0, 0), leaf::p);
}

/* ************************************************************************* */
// Test with multiple compositions on duplicate keys
struct Combine {
  double a, b;
  Combine(double a, double b) : a(a), b(b) {}
  double operator()(const double& x, const double& y, OptionalJacobian<1, 1> H1,
                    OptionalJacobian<1, 1> H2) {
    if (H1) (*H1) << a;
    if (H2) (*H2) << b;
    return a * x + b * y;
  }
};

TEST(Expression, testMultipleCompositions) {
  const double tolerance = 1e-5;
  const double fd_step = 1e-5;

  Values values;
  values.insert(1, 10.0);
  values.insert(2, 20.0);

  Expression<double> v1_(Key(1));
  Expression<double> v2_(Key(2));

  // BinaryExpression(1,2)
  //   Leaf, key = 1
  //   Leaf, key = 2
  Expression<double> sum1_(Combine(1, 2), v1_, v2_);
  EXPECT(sum1_.keys() == list_of(1)(2));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum1_, values, fd_step, tolerance);

  // BinaryExpression(3,4)
  //   BinaryExpression(1,2)
  //     Leaf, key = 1
  //     Leaf, key = 2
  //   Leaf, key = 1
  Expression<double> sum2_(Combine(3, 4), sum1_, v1_);
  EXPECT(sum2_.keys() == list_of(1)(2));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum2_, values, fd_step, tolerance);

  // BinaryExpression(5,6)
  //   BinaryExpression(3,4)
  //     BinaryExpression(1,2)
  //       Leaf, key = 1
  //       Leaf, key = 2
  //     Leaf, key = 1
  //   BinaryExpression(1,2)
  //     Leaf, key = 1
  //     Leaf, key = 2
  Expression<double> sum3_(Combine(5, 6), sum1_, sum2_);
  EXPECT(sum3_.keys() == list_of(1)(2));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum3_, values, fd_step, tolerance);
}

/* ************************************************************************* */
// Another test, with Ternary Expressions
static double combine3(const double& x, const double& y, const double& z,
                        OptionalJacobian<1, 1> H1, OptionalJacobian<1, 1> H2,
                        OptionalJacobian<1, 1> H3) {
  if (H1) (*H1) << 1.0;
  if (H2) (*H2) << 2.0;
  if (H3) (*H3) << 3.0;
  return x + 2.0 * y + 3.0 * z;
}

TEST(Expression, testMultipleCompositions2) {
  const double tolerance = 1e-5;
  const double fd_step = 1e-5;

  Values values;
  values.insert(1, 10.0);
  values.insert(2, 20.0);
  values.insert(3, 30.0);

  Expression<double> v1_(Key(1));
  Expression<double> v2_(Key(2));
  Expression<double> v3_(Key(3));

  Expression<double> sum1_(Combine(4,5), v1_, v2_);
  EXPECT(sum1_.keys() == list_of(1)(2));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum1_, values, fd_step, tolerance);

  Expression<double> sum2_(combine3, v1_, v2_, v3_);
  EXPECT(sum2_.keys() == list_of(1)(2)(3));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum2_, values, fd_step, tolerance);

  Expression<double> sum3_(combine3, v3_, v2_, v1_);
  EXPECT(sum3_.keys() == list_of(1)(2)(3));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum3_, values, fd_step, tolerance);

  Expression<double> sum4_(combine3, sum1_, sum2_, sum3_);
  EXPECT(sum4_.keys() == list_of(1)(2)(3));
  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum4_, values, fd_step, tolerance);
}

/* ************************************************************************* */
// Test multiplication with the inverse of a matrix
TEST(ExpressionFactor, MultiplyWithInverse) {
  auto model = noiseModel::Isotropic::Sigma(3, 1);

  // Create expression
  Vector3_ f_expr(MultiplyWithInverse<3>(), Expression<Matrix3>(0), Vector3_(1));

  // Check derivatives
  Values values;
  Matrix3 A = Vector3(1, 2, 3).asDiagonal();
  A(0, 1) = 0.1;
  A(0, 2) = 0.1;
  const Vector3 b(0.1, 0.2, 0.3);
  values.insert<Matrix3>(0, A);
  values.insert<Vector3>(1, b);
  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);
  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);
}

/* ************************************************************************* */
// Test multiplication with the inverse of a matrix function
namespace test_operator {
Vector3 f(const Point2& a, const Vector3& b, OptionalJacobian<3, 2> H1,
          OptionalJacobian<3, 3> H2) {
  Matrix3 A = Vector3(1, 2, 3).asDiagonal();
  A(0, 1) = a.x();
  A(0, 2) = a.y();
  A(1, 0) = a.x();
  if (H1) *H1 << b.y(), b.z(), b.x(), 0, 0, 0;
  if (H2) *H2 = A;
  return A * b;
};
}

TEST(ExpressionFactor, MultiplyWithInverseFunction) {
  auto model = noiseModel::Isotropic::Sigma(3, 1);

  using test_operator::f;
  Vector3_ f_expr(MultiplyWithInverseFunction<Point2, 3>(f),
                  Expression<Point2>(0), Vector3_(1));

  // Check derivatives
  Point2 a(1, 2);
  const Vector3 b(0.1, 0.2, 0.3);
  Matrix32 H1;
  Matrix3 A;
  const Vector Ab = f(a, b, H1, A);
  CHECK(assert_equal(A * b, Ab));
  CHECK(assert_equal(
      numericalDerivative11<Vector3, Point2>(
          std::bind(f, std::placeholders::_1, b, boost::none, boost::none), a),
      H1));

  Values values;
  values.insert<Point2>(0, a);
  values.insert<Vector3>(1, b);
  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);
  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);
}

/* ************************************************************************* */
// Test N-ary variadic template
class TestNaryFactor
    : public gtsam::ExpressionFactorN<gtsam::Point3 /*return type*/,
                                      gtsam::Rot3, gtsam::Point3,
                                      gtsam::Rot3, gtsam::Point3> {
private:
  using This = TestNaryFactor;
  using Base =
      gtsam::ExpressionFactorN<gtsam::Point3 /*return type*/,
        gtsam::Rot3, gtsam::Point3, gtsam::Rot3, gtsam::Point3>;

public:
  /// default constructor
  TestNaryFactor() = default;
  ~TestNaryFactor() override = default;

  TestNaryFactor(gtsam::Key kR1, gtsam::Key kV1,  gtsam::Key kR2, gtsam::Key kV2,
    const gtsam::SharedNoiseModel &model, const gtsam::Point3& measured)
      : Base({kR1, kV1, kR2, kV2}, model, measured) {
    this->initialize(expression({kR1, kV1, kR2, kV2}));
  }

  /// @return a deep copy of this factor
  gtsam::NonlinearFactor::shared_ptr clone() const override {
    return boost::static_pointer_cast<gtsam::NonlinearFactor>(
        gtsam::NonlinearFactor::shared_ptr(new This(*this)));
  }

  // Return measurement expression
  gtsam::Expression<gtsam::Point3> expression(
      const std::array<gtsam::Key, NARY_EXPRESSION_SIZE> &keys) const override {
    gtsam::Expression<gtsam::Rot3>   R1_(keys[0]);
    gtsam::Expression<gtsam::Point3> V1_(keys[1]);
    gtsam::Expression<gtsam::Rot3>   R2_(keys[2]);
    gtsam::Expression<gtsam::Point3> V2_(keys[3]);
    return {gtsam::rotate(R1_, V1_) - gtsam::rotate(R2_, V2_)};
  }

  /** print */
  void print(const std::string &s,
             const gtsam::KeyFormatter &keyFormatter =
                 gtsam::DefaultKeyFormatter) const override {
    std::cout << s << "TestNaryFactor("
              << keyFormatter(Factor::keys_[0]) << ","
              << keyFormatter(Factor::keys_[1]) << ","
              << keyFormatter(Factor::keys_[2]) << ","
              << keyFormatter(Factor::keys_[3]) << ")\n";
    gtsam::traits<gtsam::Point3>::Print(measured_, "  measured: ");
    this->noiseModel_->print("  noise model: ");
  }

  /** equals */
  bool equals(const gtsam::NonlinearFactor &expected,
              double tol = 1e-9) const override {
    const This *e = dynamic_cast<const This *>(&expected);
    return e != nullptr && Base::equals(*e, tol) &&
      gtsam::traits<gtsam::Point3>::Equals(measured_,e->measured_, tol);
  }

private:
  /** Serialization function */
  friend class boost::serialization::access;
  template <class ARCHIVE>
  void serialize(ARCHIVE &ar, const unsigned int /*version*/) {
    ar &boost::serialization::make_nvp(
        "TestNaryFactor",
        boost::serialization::base_object<Base>(*this));
    ar &BOOST_SERIALIZATION_NVP(measured_);
  }
};

TEST(ExpressionFactor, variadicTemplate) {
  using gtsam::symbol_shorthand::R;
  using gtsam::symbol_shorthand::V;

  // Create factor
  TestNaryFactor f(R(0),V(0), R(1), V(1), noiseModel::Unit::Create(3), Point3(0,0,0));

  // Create some values
  Values values;
  values.insert(R(0), Rot3::Ypr(0.1, 0.2, 0.3));
  values.insert(V(0), Point3(1, 2, 3));
  values.insert(R(1), Rot3::Ypr(0.2, 0.5, 0.2));
  values.insert(V(1), Point3(5, 6, 7));

  // Check unwhitenedError
  std::vector<Matrix> H(4);
  Vector actual = f.unwhitenedError(values, H);
  EXPECT_LONGS_EQUAL(4, H.size());
  EXPECT(assert_equal(Eigen::Vector3d(-5.63578115, -4.85353243, -1.4801204), actual, 1e-5));

  EXPECT_CORRECT_FACTOR_JACOBIANS(f, values, 1e-8, 1e-5);
}

TEST(ExpressionFactor, crossProduct) {
  auto model = noiseModel::Isotropic::Sigma(3, 1);

  // Create expression
  const auto a = Vector3_(1);
  const auto b = Vector3_(2);
  Vector3_ f_expr = cross(a, b);

  // Check derivatives
  Values values;
  values.insert(1, Vector3(0.1, 0.2, 0.3));
  values.insert(2, Vector3(0.4, 0.5, 0.6));
  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);
  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);
}

TEST(ExpressionFactor, dotProduct) {
  auto model = noiseModel::Isotropic::Sigma(1, 1);

  // Create expression
  const auto a = Vector3_(1);
  const auto b = Vector3_(2);
  Double_ f_expr = dot(a, b);

  // Check derivatives
  Values values;
  values.insert(1, Vector3(0.1, 0.2, 0.3));
  values.insert(2, Vector3(0.4, 0.5, 0.6));
  ExpressionFactor<double> factor(model, .0, f_expr);
  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);
}

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

max_stars_repo_name: asa/gtsam

max_issues_repo_name: asa/gtsam

max_forks_repo_name: asa/gtsam


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_CODEC_IMPL_DEFLATE_SERVICE_IPP
#define BOOST_HTTP_PROTO_CODEC_IMPL_DEFLATE_SERVICE_IPP

#include <boost/http_proto/codec/deflate_service.hpp>
#include <boost/http_proto/context.hpp>
#include <boost/http_proto/codec/codecs.hpp>
#include <boost/http_proto/codec/decoder.hpp>
#include <boost/http_proto/codec/encoder.hpp>

#if 0
#include <boost/beast/zlib/deflate_stream.hpp>
#include <boost/beast/zlib/inflate_stream.hpp>
#endif

namespace boost {
namespace http_proto {

namespace detail {

class deflate_decoder_service_impl
    : public context::service
    , public decoder_type
{
public:
    explicit
    deflate_decoder_service_impl(
        context& ctx)
    {
        ctx.codecs().add_decoder(
            "deflate", *this);
    }

    class decoder_impl
        : public decoder
    {
#if 0
        beast::zlib::inflate_stream is_;
#endif

    public:
        void
        exchange(
            buffers& b,
            error_code& ec)
        {
            (void)b;
            (void)ec;
#if 0
            beast::zlib::z_params zs;
            zs.next_in = b.input;
            zs.avail_in = b.input_avail;
            zs.total_in = 0;
            zs.next_out = b.output;
            zs.avail_out = b.output_avail;
            zs.total_out = 0;

            is_.write(zs,
                beast::zlib::Flush::none,
                    ec);

            b.input = static_cast<
                char const*>(zs.next_in);
            b.input_avail = zs.avail_in;
            b.input_used = zs.total_in;
            b.output = static_cast<
                char*>(zs.next_out);
            b.output_avail = zs.avail_out;
            b.output_used = zs.total_out;
#endif
        }
    };

    std::unique_ptr<decoder>
    make_decoder() override
    {
        return std::unique_ptr<decoder>(
            new decoder_impl());
    }
};

//------------------------------------------------

class deflate_encoder_service_impl
    : public context::service
    , public encoder_type
{
public:
    explicit
    deflate_encoder_service_impl(
        context& ctx)
    {
        ctx.codecs().add_encoder(
            "deflate", *this);
    }

    class encoder_impl
        : public encoder
    {
#if 0
        beast::zlib::deflate_stream is_;
#endif

    public:
        void
        exchange(
            buffers& b,
            error_code& ec)
        {
            (void)b;
            (void)ec;
        }
    };

    std::unique_ptr<encoder>
    make_encoder() override
    {
        return std::unique_ptr<encoder>(
            new encoder_impl());
    }
};

} // detail

//------------------------------------------------

void
install_deflate_encoder(
    context& ctx)
{
    (void)ctx;
}

void
install_deflate_decoder(
    context& ctx)
{
    make_service<
        detail::deflate_decoder_service_impl>(ctx);
}

} // http_proto
} // boost

#endif

ext: ipp


text:
#include <database.hpp>
#include <error.hpp>
#include <config.hpp>
#include <cache.hpp>
#include <games.hpp>
#include <challonge.hpp>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <boost/filesystem.hpp>

namespace opt = gears::optparse;
namespace fs  = boost::filesystem;

namespace hypest {
struct username_mapping {
    std::string challonge;
    std::string reddit;
};

struct mapping_action {
    username_mapping operator()(const std::string&, const std::string& value) const {
        username_mapping result;
        auto&& pos = value.find(',');
        if(pos == value.npos) {
            throw std::runtime_error("invalid format given, must be challonge,reddit");
        }
        result.challonge = value.substr(0, pos);
        result.reddit = value.substr(pos + 1);
        return result;
    }
};

opt::subcommand database() {
    opt::option_set args = {
        { "rank", 'r', "updates the rating period with the given bracket", opt::value<std::string>("url") },
        { "force", 'f', "force updating despite being the url(s) being processed already" },
        { "commit", 'c', "finalises a rating period and updates player's rankings" },
        { "rebuild", "rebuilds the database with the db.cache file" },
        { "verbose", "verbose output" },
        { "dump", "dumps the tournament response JSON to stdout and exits", opt::value<std::string>("url") },
        { "reddit-mapping", "updates the reddit username mapping with a .json file", opt::value<std::string>("file") },
        { "reddit", "updates the reddit username of a challonge username (e.g. \"challonge,reddit\")", opt::custom<username_mapping>(mapping_action{}) },
        { "latest", "prints information about thhe latest entry to the cache" }
    };

    opt::subcommand result = { "database", "handles the hypest database", args };
    result.description = "Updates, deletes, or otherwise fiddles with the Hypest database that keeps track of matches\n"
                         "\nIn order to add things to the rating period you must use --rank <url> for every bracket."
                         "Once the rating period is seemingly complete, use --commit to finalise the rating period";
    return result;
}

void rebuild_database(const rank_cache& cache, bool verbose) {
    if(fs::exists("rating_period.cache")) {
        std::cerr << "hypest: warning: rating period is currently in place\n";
    }

    // clear the databases
    fs::remove_all("database");

    unsigned rating_period = 1;
    for(auto&& entry : cache) {
        if(entry.rating_period != rating_period) {
            if(verbose) {
                std::cout << "Rating period (" << rating_period << ") has completed\n";
            }
            commit();
            ++rating_period;
        }
        if(verbose) {
            std::cout << "Processing " << entry.url << '\n';
        }
        rank(entry.url);
    }
    if(cache.current_rating_period > rating_period) {
        if(verbose) {
            std::cout << "Rating period (" << rating_period << ") has completed\n";
        }
        commit();
    }
}

void latest_info(const rank_cache& cache) {
    auto size = cache.size();
    auto needle = std::find_if(cache.begin(), cache.end(), [&size](const auto& entry) {
        return entry.id == size;
    });

    if(needle == cache.end()) {
        std::cout << "No last tournament found!\n";
        return;
    }

    auto&& entry = *needle;
    auto tournament = get_tournament(get_config(), entry.url);

    std::cout << "Full URL     : " << entry.url << '\n'
              << "Entry ID     : " << entry.id << '\n'
              << "Rating Period: " << entry.rating_period << '\n'
              << "Entry Date   : " << tournament["completed_at"].as<std::string>("unknown") << '\n'
              << "Game Name    : " << tournament["game_name"].as<std::string>("unknown") << '\n'
              << "Participants : " << tournament["participants_count"].as<int>(0) << '\n'
              << "Type         : " << tournament["tournament_type"].as<std::string>("unknown") << '\n'
              << "Teams allowed? " << (tournament["teams"].as<bool>(false) ? "Yes\n" : "No\n");
}

void reddit_mapping(const std::string& filename) {
    // parse the JSON file
    json::value v;
    std::ifstream in(filename);
    json::parse(in, v);
    if(not v.is<json::object>()) {
        throw fatal_error("reddit mapping JSON must be an object of key value pairs of challonge:reddit");
    }

    auto&& obj = v.as<json::object>();
    auto smash_games = games();
    for(auto&& smash : smash_games) {
        auto users = get_users(smash);
        for(auto&& u : users) {
            auto username = u.first;
            auto it = obj.find(username);
            if(it != obj.end() && it->second.is<std::string>()) {
                u.second.reddit = it->second.as<std::string>();
            }
        }
        update_users(users, smash);
    }
}

void update_reddit(const username_mapping& mapping) {
    auto smash_games = games();
    for(auto&& smash : smash_games) {
        auto users = get_users(smash);
        auto it = users.find(mapping.challonge);
        if(it != users.end()) {
            it->second.reddit = mapping.reddit;
        }
        update_users(users, smash);
    }
}

void database(const opt::arguments& args) {
    auto&& opts = args.options;
    rank_cache cache = get_cache();
    bool forced = opts.is_active("force");
    bool verbose = opts.is_active("verbose");

    if(opts.is_active("dump")) {
        auto tournament = get_tournament(get_config(), opts.get<std::string>("dump"));
        json::format_options opt;
        opt.precision = 15;
        json::dump(std::cout, tournament, opt);
        return;
    }

    if(opts.is_active("rank")) {
        auto&& url = opts.get<std::string>("rank");
        if(not forced) {
            if(cache.in(url)) {
                auto notes = {
                    "use --force to reprocess"
                };
                throw noted_error("bracket has already been processed", notes);
            }
            cache.add(url);
        }
        if(verbose) {
            std::cout << "Processing " << url << '\n';
        }
        rank(url);
    }

    if(opts.is_active("latest")) {
        latest_info(cache);
    }

    if(opts.is_active("reddit")) {
        update_reddit(opts.get<username_mapping>("reddit"));
    }

    if(opts.is_active("reddit-mapping")) {
        reddit_mapping(opts.get<std::string>("reddit-mapping"));
    }

    if(opts.is_active("rebuild")) {
        // sort database by rating period
        std::sort(std::begin(cache), std::end(cache), [](const auto& lhs, const auto& rhs) {
            return lhs.rating_period < rhs.rating_period;
        });
        rebuild_database(cache, verbose);
        return;
    }

    if(opts.is_active("commit")) {
        commit();
    }

    if(not forced) {
        if(opts.is_active("commit")) {
            ++cache.current_rating_period;
        }
        if(verbose) {
            std::cout << "Updating cache...\n";
        }
        update_cache(cache);
    }
}
} // hypest

ext: cpp

max_stars_repo_name: HypestTeam/Hypest

max_issues_repo_name: HypestTeam/Hypest

max_forks_repo_name: HypestTeam/Hypest


text:
#include <boost/test/unit_test.hpp>

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "PeriodVal.h"
#include "PatternScannerEngine.h"
#include "SegmentConstraint.h"
#include "SegmentValsCloseToLinearEq.h"
#include "SegmentListConstraint.h"
#include "SlopeIncreasesConstraint.h"
#include "PatternMatchValidator.h"
#include "EndWithinPercentOfStart.h"
#include "PeriodValSegment.h"
#include "DoubleBottomScanner.h"
#include "TestHelper.h"
#include "MultiPatternScanner.h"

using namespace boost::posix_time;
using namespace boost::gregorian;
using namespace testHelper;

BOOST_AUTO_TEST_CASE( DoubleBottomScanner_QCOR_20130819 )
{
	// Test a full double-bottom scan for QCOR in 2013. This unit test is built up from
	// VScanner_QCOR_20130819_LHSofDoubleBottom and VScanner_QCOR_20130819_RHSofDoubleBottom, which
	// test the LHS and RHS of the double-bottom individually. The number of pattern matches
	// should therefore be the number of matches from VScanner_QCOR_20130819_LHSofDoubleBottom
	// multiplied times the number of matches from VScanner_QCOR_20130819_RHSofDoubleBottom.

	PeriodValSegmentPtr chartData = PeriodValSegment::readFromFile("./patternScan/QCOR_DoubleBottom_Weekly.csv");
	genPeriodValSegmentInfo("Double bottom segment data",*chartData);

	DoubleBottomScanner scanner(DoubleRange(7.0,40.0)); // allow for a deeper depth than the default
	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);

	verifyMatchList("Double bottom match",patternMatches,1);

	verifyPatternMatch("Double bottom match",
            ptime(date(2013,8,26)),ptime(date(2014,2,10)),4,patternMatches->front());

}

BOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized )
{
	using namespace boost::gregorian;

	TestPerValRangeList ranges;
	ranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend
	ranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend
	ranges.push_back(TestPerValRange(3,97.5,91.5)); // next down-trend, going below the initial down-trend
	ranges.push_back(TestPerValRange(4,92.0,100.5)); // final uptrend, goes above start
	PeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);

	DoubleBottomScanner scanner;
	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);

    verifyMatchList("DoubleBottom_Synthesized",patternMatches,2);
	verifyPatternMatch("DoubleBottom_Synthesized match",
            ptime(date(2014,1,1)),ptime(date(2014,1,13)),4,patternMatches->front());

}

BOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized_RHSHigherLow )
{
	using namespace boost::gregorian;

	TestPerValRangeList ranges;
	ranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend
	ranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend
	ranges.push_back(TestPerValRange(3,97.5,92.5)); // next down-trend, *not* going below the initial down-trend
	ranges.push_back(TestPerValRange(4,93.0,100.5)); // final uptrend, goes above start
	PeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);

	DoubleBottomScanner scanner;
	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);

	BOOST_TEST_MESSAGE("Should return 0 matches, since the lowest low on the RHS is not lower than the LHS");
	verifyMatchList("DoubleBottom_Synthesized_RHSHigherLow",patternMatches,0);

}

BOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized_MinMaxDepth )
{
	using namespace boost::gregorian;

	TestPerValRangeList ranges;
	ranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend
	ranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend
	ranges.push_back(TestPerValRange(3,97.5,91.5)); // next down-trend, going below the initial down-trend
	ranges.push_back(TestPerValRange(4,92.0,100.5)); // final uptrend, goes above start
	PeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);

	DoubleBottomScanner scanner(DoubleRange(9.0,30.0)); // Require at least a 10% depth to trigger depth constraints
	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);

	BOOST_TEST_MESSAGE("Should return 0 matches, since the depth is not greater than 9%");
	verifyMatchList("DoubleBottom_Synthesized_ShallowDepth",patternMatches,0);

	DoubleBottomScanner scannerMaxDepth(DoubleRange(4.0,7.0)); // Require at least a 10% depth to trigger depth constraints
	patternMatches = scanner.scanPatternMatches(chartData);

	BOOST_TEST_MESSAGE("Should return 0 matches, since the depth is greater than 7%");
	verifyMatchList("DoubleBottom_Synthesized_ShallowDepth",patternMatches,0);

}

BOOST_AUTO_TEST_CASE( DoubleBottomScanner_GBX )
{
    PeriodValSegmentPtr chartData = PeriodValSegment::readFromFile("./patternScan/GBX_Daily.csv");
    genPeriodValSegmentInfo("Double bottom segment data",*chartData);

    MultiPatternScanner scanner(PatternScannerPtr(new DoubleBottomScanner(DoubleRange(7.0,40.0))));

    PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);

    // Shouldn't match any double bottoms. The potential double bottom in this pattern data
    // has a middle which goes higher than the beginning of the pattern, and is thus mal-formed.
    verifyMatchList("Double bottom match",patternMatches,0);

}

max_stars_repo_name: sroehling/ChartPatternRecognitionLib

max_issues_repo_name: sroehling/ChartPatternRecognitionLib

max_forks_repo_name: sroehling/ChartPatternRecognitionLib


text:
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <string.h>
#include <fstream>
#include <sstream>
#include <boost/test/included/unit_test_framework.hpp>

#include "code.hh"
#include "OutputStreamer.hh"
#include "InputStreamer.hh"
#include "Serializer.hh"
#include "Writer.hh"
#include "ValidatingWriter.hh"
#include "Reader.hh"
#include "ValidatingReader.hh"
#include "ValidSchema.hh"
#include "Compiler.hh"

void serialize(const avrouser::RootRecord &rec)
{
    avro::ScreenStreamer os;
    avro::Writer writer(os);

    avro::serialize(writer, rec);
}

void serializeValid(const avro::ValidSchema &valid, const avrouser::RootRecord &rec)
{
    avro::ScreenStreamer os;
    avro::ValidatingWriter writer(valid, os);

    avro::serialize(writer, rec);
}

void checkArray(const avrouser::Array_of_double &a1, const avrouser::Array_of_double &a2)
{
    BOOST_CHECK_EQUAL(a1.value.size(), 3U);
    BOOST_CHECK_EQUAL(a1.value.size(), a2.value.size());
    for(size_t i = 0; i < a1.value.size(); ++i) {
        BOOST_CHECK_EQUAL(a1.value[i], a2.value[i]);
    }
}

void checkMap(const avrouser::Map_of_int &map1, const avrouser::Map_of_int &map2)
{
    BOOST_CHECK_EQUAL(map1.value.size(), map2.value.size());
    avrouser::Map_of_int::MapType::const_iterator iter1 = map1.value.begin();
    avrouser::Map_of_int::MapType::const_iterator end   = map1.value.end();
    avrouser::Map_of_int::MapType::const_iterator iter2 = map2.value.begin();

    while(iter1 != end) {
        BOOST_CHECK_EQUAL(iter1->first, iter2->first);
        BOOST_CHECK_EQUAL(iter1->second, iter2->second);
        ++iter1;
        ++iter2;
    }
}

void checkBytes(const std::vector<uint8_t> &v1, const std::vector<uint8_t> &v2)
{
    BOOST_CHECK_EQUAL(v1.size(), 2U);
    BOOST_CHECK_EQUAL(v1.size(), v2.size());
    for(size_t i = 0; i < v1.size(); ++i) {
        BOOST_CHECK_EQUAL(v1[i], v2[i]);
    }
}

void checkOk(const avrouser::RootRecord &rec1, const avrouser::RootRecord &rec2)
{
    BOOST_CHECK_EQUAL(rec1.mylong, rec1.mylong);
    checkMap(rec1.mymap, rec2.mymap);
    checkArray(rec1.myarray, rec2.myarray);

    BOOST_CHECK_EQUAL(rec1.myenum.value, rec2.myenum.value);

    BOOST_CHECK_EQUAL(rec1.myunion.choice, rec2.myunion.choice);
    // in this test I know choice was 1
    {
        BOOST_CHECK_EQUAL(rec1.myunion.choice, 1);
        checkMap(rec1.myunion.getValue<avrouser::Map_of_int>(), rec2.myunion.getValue<avrouser::Map_of_int>());
    }

    BOOST_CHECK_EQUAL(rec1.anotherunion.choice, rec2.anotherunion.choice);
    // in this test I know choice was 0
    {
        BOOST_CHECK_EQUAL(rec1.anotherunion.choice, 0);
        typedef std::vector<uint8_t> mytype;
        checkBytes(rec1.anotherunion.getValue<mytype>(), rec2.anotherunion.getValue<avrouser::Union_of_bytes_null::T0>());
    }

    BOOST_CHECK_EQUAL(rec1.mybool, rec2.mybool);
    for(int i = 0; i < static_cast<int>(avrouser::md5::fixedSize); ++i) {
        BOOST_CHECK_EQUAL(rec1.myfixed.value[i], rec2.myfixed.value[i]);
    }
    BOOST_CHECK_EQUAL(rec1.anotherint, rec1.anotherint);

}

void testParser(const avrouser::RootRecord &myRecord)
{
    std::ostringstream ostring;
    avro::OStreamer os(ostring);
    avro::Writer s (os);

    avro::serialize(s, myRecord);

    avrouser::RootRecord inRecord;
    std::istringstream istring(ostring.str());
    avro::IStreamer is(istring);
    avro::Reader p(is);
    avro::parse(p, inRecord);

    checkOk(myRecord, inRecord);
}

void testParserValid(avro::ValidSchema &valid, const avrouser::RootRecord &myRecord)
{
    std::ostringstream ostring;
    avro::OStreamer os(ostring);
    avro::ValidatingWriter s (valid, os);

    avro::serialize(s, myRecord);

    avrouser::RootRecord inRecord;
    std::istringstream istring(ostring.str());
    avro::IStreamer is(istring);
    avro::ValidatingReader p(valid, is);
    avro::parse(p, inRecord);

    checkOk(myRecord, inRecord);
}

void runTests(const avrouser::RootRecord myRecord)
{
    std::cout << "Serialize:\n";
    serialize(myRecord);
    std::cout << "end Serialize\n";

    avro::ValidSchema schema;
    std::ifstream in("jsonschemas/bigrecord");
    avro::compileJsonSchema(in, schema);
    std::cout << "Serialize validated:\n";
    serializeValid(schema, myRecord);
    std::cout << "end Serialize validated\n";

    testParser(myRecord);

    testParserValid(schema, myRecord);
}

void testGen()
{
    uint8_t fixed[] =  {0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

    avrouser::RootRecord myRecord;
    myRecord.mylong = 212;
    myRecord.mymap.value.clear();
    myRecord.myarray.addValue(3434.9);
    myRecord.myarray.addValue(7343.9);
    myRecord.myarray.addValue(-63445.9);
    myRecord.myenum.value = avrouser::ExampleEnum::one;
    avrouser::Map_of_int map;
    map.addValue("one", 1);
    map.addValue("two", 2);
    myRecord.myunion.set_Map_of_int(map);
    std::vector<uint8_t> vec;
    vec.push_back(1);
    vec.push_back(2);
    myRecord.anotherunion.set_bytes(vec);
    myRecord.mybool = true;
    memcpy(myRecord.myfixed.value, fixed, avrouser::md5::fixedSize);
    myRecord.anotherint = 4534;
    myRecord.bytes.push_back(10);
    myRecord.bytes.push_back(20);

    runTests(myRecord);
}

boost::unit_test::test_suite*
init_unit_test_suite( int argc, char* argv[] )
{
    using namespace boost::unit_test;

    test_suite* test= BOOST_TEST_SUITE( "Avro C++ generated code test suite" );
    test->add( BOOST_TEST_CASE( &testGen ) );

    return test;
}

ext: cc

max_stars_repo_name: SpotifyUsedOpenSourceCode/avro

max_issues_repo_name: SpotifyUsedOpenSourceCode/avro

max_forks_repo_name: SpotifyUsedOpenSourceCode/avro


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_NEGIFNOT_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_NEGIFNOT_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-boolean
    Function object implementing negifnot capabilities

    The function returns -x if cond is @ref False and x otherwise.

    @par Semantic:

    For every parameters @c cond of type @c C and @c x of type @c T:

    @code
    T1 r = negifnot(cond,x);
    @endcode

    is similar to:

    @code
    T r = cond ? x : -x;
    @endcode

  **/
  Value negifnot(LogicalValue const& cond, Value const & x);

  //@overload
  Value negifnot(Value const& cond, Value const & x);
} }
#endif

#include <boost/simd/function/scalar/negifnot.hpp>
#include <boost/simd/function/simd/negifnot.hpp>

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
//  This class constructs the edge-expanded routing graph

#ifndef EDGE_BASED_GRAPH_FACTORY_HPP_
#define EDGE_BASED_GRAPH_FACTORY_HPP_

#include "extractor/compressed_edge_container.hpp"
#include "extractor/edge_based_edge.hpp"
#include "extractor/edge_based_node.hpp"
#include "extractor/original_edge_data.hpp"
#include "extractor/profile_properties.hpp"
#include "extractor/query_node.hpp"
#include "extractor/restriction_map.hpp"

#include "extractor/guidance/turn_analysis.hpp"
#include "extractor/guidance/turn_instruction.hpp"
#include "extractor/guidance/turn_lane_types.hpp"
#include "util/guidance/bearing_class.hpp"
#include "util/guidance/entry_class.hpp"

#include "util/deallocating_vector.hpp"
#include "util/name_table.hpp"
#include "util/node_based_graph.hpp"
#include "util/typedefs.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <queue>
#include <string>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include <boost/filesystem/fstream.hpp>

namespace osrm
{
namespace extractor
{

class ScriptingEnvironment;

namespace lookup
{
// Set to 1 byte alignment
#pragma pack(push, 1)
struct SegmentHeaderBlock
{
    std::uint32_t num_osm_nodes;
    OSMNodeID previous_osm_node_id;
};
#pragma pack(pop)
static_assert(sizeof(SegmentHeaderBlock) == 12, "SegmentHeaderBlock is not packed correctly");

#pragma pack(push, 1)
struct SegmentBlock
{
    OSMNodeID this_osm_node_id;
    double segment_length;
    std::int32_t segment_weight;
};
#pragma pack(pop)
static_assert(sizeof(SegmentBlock) == 20, "SegmentBlock is not packed correctly");

#pragma pack(push, 1)
struct PenaltyBlock
{
    std::uint32_t fixed_penalty;
    OSMNodeID from_id;
    OSMNodeID via_id;
    OSMNodeID to_id;
};
#pragma pack(pop)
static_assert(sizeof(PenaltyBlock) == 28, "PenaltyBlock is not packed correctly");
}

class EdgeBasedGraphFactory
{
  public:
    EdgeBasedGraphFactory(const EdgeBasedGraphFactory &) = delete;
    EdgeBasedGraphFactory &operator=(const EdgeBasedGraphFactory &) = delete;

    explicit EdgeBasedGraphFactory(std::shared_ptr<util::NodeBasedDynamicGraph> node_based_graph,
                                   CompressedEdgeContainer &compressed_edge_container,
                                   const std::unordered_set<NodeID> &barrier_nodes,
                                   const std::unordered_set<NodeID> &traffic_lights,
                                   std::shared_ptr<const RestrictionMap> restriction_map,
                                   const std::vector<QueryNode> &node_info_list,
                                   ProfileProperties profile_properties,
                                   const util::NameTable &name_table,
                                   std::vector<std::uint32_t> &turn_lane_offsets,
                                   std::vector<guidance::TurnLaneType::Mask> &turn_lane_masks,
                                   guidance::LaneDescriptionMap &lane_description_map);

    void Run(ScriptingEnvironment &scripting_environment,
             const std::string &original_edge_data_filename,
             const std::string &turn_lane_data_filename,
             const std::string &edge_segment_lookup_filename,
             const std::string &edge_penalty_filename,
             const bool generate_edge_lookup);

    // The following get access functions destroy the content in the factory
    void GetEdgeBasedEdges(util::DeallocatingVector<EdgeBasedEdge> &edges);
    void GetEdgeBasedNodes(std::vector<EdgeBasedNode> &nodes);
    void GetStartPointMarkers(std::vector<bool> &node_is_startpoint);
    void GetEdgeBasedNodeWeights(std::vector<EdgeWeight> &output_node_weights);

    // These access functions don't destroy the content
    const std::vector<BearingClassID> &GetBearingClassIds() const;
    std::vector<BearingClassID> &GetBearingClassIds();
    std::vector<util::guidance::BearingClass> GetBearingClasses() const;
    std::vector<util::guidance::EntryClass> GetEntryClasses() const;

    unsigned GetHighestEdgeID();

    // Basic analysis of a turn (u --(e1)-- v --(e2)-- w)
    // with known angle.
    // Handles special cases like u-turns and roundabouts
    // For basic turns, the turn based on the angle-classification is returned
    guidance::TurnInstruction AnalyzeTurn(const NodeID u,
                                          const EdgeID e1,
                                          const NodeID v,
                                          const EdgeID e2,
                                          const NodeID w,
                                          const double angle) const;

  private:
    using EdgeData = util::NodeBasedDynamicGraph::EdgeData;

    //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the
    //! graph
    std::vector<bool> m_edge_based_node_is_startpoint;

    //! node weights that indicate the length of the segment (node based) represented by the
    //! edge-based node
    std::vector<EdgeWeight> m_edge_based_node_weights;

    //! list of edge based nodes (compressed segments)
    std::vector<EdgeBasedNode> m_edge_based_node_list;
    util::DeallocatingVector<EdgeBasedEdge> m_edge_based_edge_list;
    EdgeID m_max_edge_id;

    const std::vector<QueryNode> &m_node_info_list;
    std::shared_ptr<util::NodeBasedDynamicGraph> m_node_based_graph;
    std::shared_ptr<RestrictionMap const> m_restriction_map;

    const std::unordered_set<NodeID> &m_barrier_nodes;
    const std::unordered_set<NodeID> &m_traffic_lights;
    CompressedEdgeContainer &m_compressed_edge_container;

    ProfileProperties profile_properties;

    const util::NameTable &name_table;
    std::vector<std::uint32_t> &turn_lane_offsets;
    std::vector<guidance::TurnLaneType::Mask> &turn_lane_masks;
    guidance::LaneDescriptionMap &lane_description_map;

    void CompressGeometry();
    unsigned RenumberEdges();
    void GenerateEdgeExpandedNodes();
    void GenerateEdgeExpandedEdges(ScriptingEnvironment &scripting_environment,
                                   const std::string &original_edge_data_filename,
                                   const std::string &turn_lane_data_filename,
                                   const std::string &edge_segment_lookup_filename,
                                   const std::string &edge_fixed_penalties_filename,
                                   const bool generate_edge_lookup);

    void InsertEdgeBasedNode(const NodeID u, const NodeID v);

    void FlushVectorToStream(std::ofstream &edge_data_file,
                             std::vector<OriginalEdgeData> &original_edge_data_vector) const;

    std::size_t restricted_turns_counter;
    std::size_t skipped_uturns_counter;
    std::size_t skipped_barrier_turns_counter;

    std::unordered_map<util::guidance::BearingClass, BearingClassID> bearing_class_hash;
    std::vector<BearingClassID> bearing_class_by_node_based_node;
    std::unordered_map<util::guidance::EntryClass, EntryClassID> entry_class_hash;
};
} // namespace extractor
} // namespace osrm

#endif /* EDGE_BASED_GRAPH_FACTORY_HPP_ */

max_stars_repo_name: beemogmbh/osrm-backend

max_issues_repo_name: beemogmbh/osrm-backend

max_forks_repo_name: beemogmbh/osrm-backend