/* ---------------------------------------------------------------------------- * 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 testBAD.cpp * @date September 18, 2014 * @author Frank Dellaert * @brief unit tests for Block Automatic Differentiation */ #include #include #include #include #include #include #include #include #include namespace gtsam { ///----------------------------------------------------------------------------- /// Expression node. The superclass for objects that do the heavy lifting /// An Expression has a pointer to an ExpressionNode underneath /// allowing Expressions to have polymorphic behaviour even though they /// are passed by value. This is the same way boost::function works. /// http://loki-lib.sourceforge.net/html/a00652.html template class ExpressionNode { public: ExpressionNode(){} virtual ~ExpressionNode(){} virtual void getKeys(std::set& keys) const = 0; virtual T value(const Values& values, boost::optional&> = boost::none) const = 0; virtual ExpressionNode* clone() const = 0; }; /// Constant Expression template class ConstantExpression : public ExpressionNode { T value_; public: typedef T type; /// Constructor with a value, yielding a constant ConstantExpression(const T& value) : value_(value) { } virtual ~ConstantExpression(){} virtual void getKeys(std::set& /* keys */) const {} virtual T value(const Values& values, boost::optional&> jacobians = boost::none) const { return value_; } virtual ExpressionNode* clone() const { return new ConstantExpression(*this); } }; //----------------------------------------------------------------------------- /// Leaf Expression template class LeafExpression : public ExpressionNode { Key key_; public: typedef T type; /// Constructor with a single key LeafExpression(Key key) : key_(key) { } virtual ~LeafExpression(){} virtual void getKeys(std::set& keys) const { keys.insert(key_); } virtual T value(const Values& values, boost::optional&> jacobians = boost::none) const { const T& value = values.at(key_); if( jacobians ) { std::map::iterator it = jacobians->find(key_); if(it != jacobians->end()) { it->second += Eigen::MatrixXd::Identity(value.dim(), value.dim()); } else { (*jacobians)[key_] = Eigen::MatrixXd::Identity(value.dim(), value.dim()); } } return value; } virtual ExpressionNode* clone() const { return new LeafExpression(*this); } }; //----------------------------------------------------------------------------- /// Unary Expression template class UnaryExpression : public ExpressionNode { public: typedef T (*function)(const E&, boost::optional); private: boost::shared_ptr< ExpressionNode > expression_; function f_; public: typedef T type; /// Constructor with a single key UnaryExpression(function f, const ExpressionNode& expression) : expression_(expression.clone()), f_(f) { } virtual ~UnaryExpression(){} virtual void getKeys(std::set& keys) const{ expression_->getKeys(keys); } virtual T value(const Values& values, boost::optional&> jacobians = boost::none) const { T value; if(jacobians) { Eigen::MatrixXd H; value = f_(expression_->value(values, jacobians), H); std::map::iterator it = jacobians->begin(); for( ; it != jacobians->end(); ++it) { it->second = H * it->second; } } else { value = f_(expression_->value(values), boost::none); } return value; } virtual ExpressionNode* clone() const { return new UnaryExpression(*this); } }; //----------------------------------------------------------------------------- /// Binary Expression template class BinaryExpression : public ExpressionNode { public: typedef T (*function)(const E1&, const E2&, boost::optional, boost::optional); private: boost::shared_ptr< ExpressionNode > expression1_; boost::shared_ptr< ExpressionNode > expression2_; function f_; public: typedef T type; /// Constructor with a single key BinaryExpression(function f, const ExpressionNode& expression1, const ExpressionNode& expression2) : expression1_(expression1.clone()), expression2_(expression2.clone()), f_(f) { } virtual ~BinaryExpression(){} virtual void getKeys(std::set& keys) const{ expression1_->getKeys(keys); expression2_->getKeys(keys); } virtual T value(const Values& values, boost::optional&> jacobians = boost::none) const { T val; if(jacobians) { std::map terms1; std::map terms2; Matrix H1, H2; val = f_(expression1_->value(values, terms1), expression2_->value(values, terms2), H1, H2); // TODO: both Jacobians and terms are sorted. There must be a simple // but fast algorithm that does this. typedef std::pair Pair; BOOST_FOREACH(const Pair& term, terms1) { std::map::iterator it = jacobians->find(term.first); if(it != jacobians->end()) { it->second += H1 * term.second; } else { (*jacobians)[term.first] = H1 * term.second; } } BOOST_FOREACH(const Pair& term, terms2) { std::map::iterator it = jacobians->find(term.first); if(it != jacobians->end()) { it->second += H2 * term.second; } else { (*jacobians)[term.first] = H2 * term.second; } } } else { val = f_(expression1_->value(values), expression2_->value(values), boost::none, boost::none); } return val; } virtual ExpressionNode* clone() const { return new BinaryExpression(*this); } }; template class Expression { public: Expression(const ExpressionNode& root) { root_.reset(root.clone()); } // Initialize a constant expression Expression(const T& value) : root_(new ConstantExpression(value)){ } // Initialize a leaf expression Expression(const Key& key) : root_(new LeafExpression(key)) {} /// Initialize a unary expression template Expression(typename UnaryExpression::function f, const Expression& expression) { // TODO Assert that root of expression is not null. root_.reset(new UnaryExpression(f, *expression.root())); } /// Initialize a binary expression template Expression(typename BinaryExpression::function f, const Expression& expression1, const Expression& expression2) { // TODO Assert that root of expressions 1 and 2 are not null. root_.reset(new BinaryExpression(f, *expression1.root(), *expression2.root())); } void getKeys(std::set& keys) const { root_->getKeys(keys); } T value(const Values& values, boost::optional&> jacobians = boost::none) const { return root_->value(values, jacobians); } const boost::shared_ptr >& root() const{ return root_; } private: boost::shared_ptr > root_; }; //----------------------------------------------------------------------------- void printPair(std::pair pair) { std::cout << pair.first << ": " << pair.second << std::endl; } // usage: std::for_each(terms.begin(), terms.end(), printPair); //----------------------------------------------------------------------------- /// AD Factor template class BADFactor: NonlinearFactor { const T measurement_; const Expression expression_; /// get value from expression and calculate error with respect to measurement Vector unwhitenedError(const Values& values) const { const T& value = expression_.value(values); return value.localCoordinates(measurement_); } public: /// Constructor BADFactor(const T& measurement, const Expression& expression) : measurement_(measurement), expression_(expression) { } /// Constructor BADFactor(const T& measurement, const ExpressionNode& expression) : measurement_(measurement), expression_(expression) { } /** * Calculate the error of the factor. * This is the log-likelihood, e.g. \f$ 0.5(h(x)-z)^2/\sigma^2 \f$ in case of Gaussian. * In this class, we take the raw prediction error \f$ h(x)-z \f$, ask the noise model * to transform it to \f$ (h(x)-z)^2/\sigma^2 \f$, and then multiply by 0.5. */ virtual double error(const Values& values) const { if (this->active(values)) { const Vector e = unwhitenedError(values); return 0.5 * e.squaredNorm(); } else { return 0.0; } } /// get the dimension of the factor (number of rows on linearization) size_t dim() const { return 0; } /// linearize to a GaussianFactor boost::shared_ptr linearize(const Values& values) const { // We will construct an n-ary factor below, where terms is a container whose // value type is std::pair, specifying the // collection of keys and matrices making up the factor. std::map terms; expression_.value(values, terms); Vector b = unwhitenedError(values); SharedDiagonal model = SharedDiagonal(); return boost::shared_ptr( new JacobianFactor(terms, b, model)); } }; } using namespace std; using namespace gtsam; /* ************************************************************************* */ Point3 transformTo(const Pose3& x, const Point3& p, boost::optional Dpose, boost::optional Dpoint) { return x.transform_to(p, Dpose, Dpoint); } Point2 project(const Point3& p, boost::optional Dpoint) { return PinholeCamera::project_to_camera(p, Dpoint); } template Point2 uncalibrate(const CAL& K, const Point2& p, boost::optional Dcal, boost::optional Dp) { return K.uncalibrate(p, Dcal, Dp); } /* ************************************************************************* */ TEST(BAD, test) { // 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 Point2 measured(-17, 30); SharedNoiseModel model = noiseModel::Unit::Create(2); GeneralSFMFactor2 old(measured, model, 1, 2, 3); double expected_error = old.error(values); GaussianFactor::shared_ptr expected = old.linearize(values); // Create leaves Expression x(1); Expression p(2); Expression K(3); // Create expression tree Expression p_cam(transformTo, x, p); Expression projection(project, p_cam); Expression uv_hat(uncalibrate, K, projection); // Check getKeys std::set keys; uv_hat.getKeys(keys); EXPECT_LONGS_EQUAL(3, keys.size()); // Create factor BADFactor f(measured, uv_hat); // Check value EXPECT_DOUBLES_EQUAL(expected_error, f.error(values), 1e-9); // Check dimension EXPECT_LONGS_EQUAL(0, f.dim()); // Check linearization boost::shared_ptr gf = f.linearize(values); EXPECT( assert_equal(*expected, *gf, 1e-9)); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */