Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NormalError cost function #44

Merged
merged 3 commits into from
May 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions _pyceres/factors/bindings.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,55 @@

namespace py = pybind11;

inline Eigen::MatrixXd SqrtInformation(const Eigen::MatrixXd& covariance) {
return covariance.inverse().llt().matrixL();
}

// Mahalanobis squared distance between two parameters.
class NormalError {
public:
explicit NormalError(const Eigen::MatrixXd& covariance)
: sqrt_information_(SqrtInformation(covariance)) {
THROW_CHECK_EQ(covariance.rows(), covariance.cols());
}

static ceres::CostFunction* Create(const Eigen::MatrixXd& covariance) {
auto* cost_function = new ceres::DynamicAutoDiffCostFunction<NormalError>(
new NormalError(covariance));
const int dimension = covariance.rows();
cost_function->AddParameterBlock(dimension);
cost_function->AddParameterBlock(dimension);
cost_function->SetNumResiduals(dimension);
return cost_function;
}

template <typename T>
bool operator()(T const* const* parameters, T* residuals_ptr) const {
const int dimension = sqrt_information_.rows();
for (int i = 0; i < dimension; ++i) {
residuals_ptr[i] = parameters[0][i] - parameters[1][i];
}
Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> residuals(residuals_ptr,
dimension);
residuals.applyOnTheLeft(sqrt_information_.template cast<T>());
return true;
}

private:
const Eigen::MatrixXd sqrt_information_;
};

void BindFactors(py::module& m) {
m.def(
"NormalPrior",
[](const Eigen::VectorXd& mean,
const Eigen::Matrix<double, -1, -1>& covariance) {
const Eigen::MatrixXd& covariance) -> ceres::CostFunction* {
THROW_CHECK_EQ(covariance.cols(), mean.size());
THROW_CHECK_EQ(covariance.cols(), covariance.rows());
return new ceres::NormalPrior(covariance.inverse().llt().matrixL(),
mean);
return new ceres::NormalPrior(SqrtInformation(covariance), mean);
},
py::arg("mean"),
py::arg("covariance"));

m.def("NormalError", &NormalError::Create, py::arg("covariance"));
}
Loading