ceres中的ConditionedCostFuntion源码阅读
class ConditionedCostFuntion
这个类的作用是给隐藏代价函数(cost function)的残差值赋上不同的权值。举个简单的例子:你有一个产生了N个残差值的代价函数,但是你想要残差的总体值不是简单的等于每个参加的平方和,你想给每一个残差一个特定的权值(尺度),来改变每个残差对总体参加的贡献。
// my_cost_function produces N residuals
CostFunction* my_cost_function = ...
CHECK_EQ(N, my_cost_function->num_residuals());
vector<CostFunction*> conditioners;
// Make N 1x1 cost functions (1 parameter, 1 residual)
CostFunction* f_1 = ...
conditioners.push_back(f_1);
CostFunction* f_N = ... conditioners.push_back(f_N);
ConditionedCostFunction* ccf =
new ConditionedCostFunction(my_cost_function, conditioners);
这样,ccf的residual[i]可以从第i个conditioner中传出
ccf_residual[i] = f_i(my_cost_function_residual[i])
相应的,Jacobian会被合理的影响。
下面贴上源码,头文件,CPP及官方test
一目了然,正如遇事不决,读源码
//
// Author: wjr@google.com (William Rucklidge)
//
// This file contains a cost function that can apply a transformation to
// each residual value before they are square-summed.
#ifndef CERES_PUBLIC_CONDITIONED_COST_FUNCTION_H_
#define CERES_PUBLIC_CONDITIONED_COST_FUNCTION_H_
#include <memory>
#include <vector>
#include "ceres/cost_function.h"
#include "ceres/internal/disable_warnings.h"
#include "ceres/types.h"
namespace ceres {
// This class allows you to apply different conditioning to the residual
// values of a wrapped cost function. An example where this is useful is
// where you have an existing cost function that produces N values, but you
// want the total cost to be something other than just the sum of these
// squared values - maybe you want to apply a different scaling to some
// values, to change their contribution to the cost.
//
// Usage:
//
// // my_cost_function produces N residuals
// CostFunction* my_cost_function = ...
// CHECK_EQ(N, my_cost_function->num_residuals());
// vector<CostFunction*> conditioners;
//
// // Make N 1x1 cost functions (1 parameter, 1 residual)
// CostFunction* f_1 = ...
// conditioners.push_back(f_1);
// ...
// CostFunction* f_N = ...
// conditioners.push_back(f_N);
// ConditionedCostFunction* ccf =
// new ConditionedCostFunction(my_cost_function, conditioners);
//
// Now ccf's residual i (i=0..N-1) will be passed though the i'th conditioner.
//
// ccf_residual[i] = f_i(my_cost_function_residual[i])
//
// and the Jacobian will be affected appropriately.
class CERES_EXPORT ConditionedCostFunction : public CostFunction {
public:
// Builds a cost function based on a wrapped cost function, and a
// per-residual conditioner. Takes ownership of all of the wrapped cost
// functions, or not, depending on the ownership parameter. Conditioners
// may be NULL, in which case the corresponding residual is not modified.
//
// The conditioners can repeat.
ConditionedCostFunction(CostFunction* wrapped_cost_function,
const std::vector<CostFunction*>& conditioners,
Ownership ownership);
virtual ~ConditionedCostFunction();
bool Evaluate(double const* const* parameters,
double* residuals,
double** jacobians) const override;
private:
std::unique_ptr<CostFunction> wrapped_cost_function_;
std::vector<CostFunction*> conditioners_;
Ownership ownership_;
};
} // namespace ceres
#include "ceres/internal/reenable_warnings.h"
#endif // CERES_PUBLIC_CONDITIONED_COST_FUNCTION_H_
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: wjr@google.com (William Rucklidge)
//
// Tests for the conditioned cost function.
#include "ceres/conditioned_cost_function.h"
#include "ceres/internal/eigen.h"
#include "ceres/normal_prior.h"
#include "ceres/types.h"
#include "gtest/gtest.h"
namespace ceres {
namespace internal {
// The size of the cost functions we build.
static const int kTestCostFunctionSize = 3;
// A simple cost function: return ax + b.
class LinearCostFunction : public CostFunction {
public:
LinearCostFunction(double a, double b) : a_(a), b_(b) {
set_num_residuals(1);
mutable_parameter_block_sizes()->push_back(1);
}
bool Evaluate(double const* const* parameters,
double* residuals,
double** jacobians) const final {
*residuals = **parameters * a_ + b_;
if (jacobians && *jacobians) {
**jacobians = a_;
}
return true;
}
private:
const double a_, b_;
};
// Tests that ConditionedCostFunction does what it's supposed to.
TEST(ConditionedCostFunction, NormalOperation) {
double v1[kTestCostFunctionSize], v2[kTestCostFunctionSize],
jac[kTestCostFunctionSize * kTestCostFunctionSize],
result[kTestCostFunctionSize];
for (int i = 0; i < kTestCostFunctionSize; i++) {
v1[i] = i;
v2[i] = i * 10;
// Seed a few garbage values in the Jacobian matrix, to make sure that
// they're overwritten.
jac[i * 2] = i * i;
result[i] = i * i * i;
}
// Make a cost function that computes x - v2
VectorRef v2_vector(v2, kTestCostFunctionSize, 1);
Matrix identity(kTestCostFunctionSize, kTestCostFunctionSize);
identity.setIdentity();
NormalPrior* difference_cost_function = new NormalPrior(identity, v2_vector);
std::vector<CostFunction*> conditioners;
for (int i = 0; i < kTestCostFunctionSize; i++) {
conditioners.push_back(new LinearCostFunction(i + 2, i * 7));
}
ConditionedCostFunction conditioned_cost_function(
difference_cost_function, conditioners, TAKE_OWNERSHIP);
EXPECT_EQ(difference_cost_function->num_residuals(),
conditioned_cost_function.num_residuals());
EXPECT_EQ(difference_cost_function->parameter_block_sizes(),
conditioned_cost_function.parameter_block_sizes());
double* parameters[1];
parameters[0] = v1;
double* jacs[1];
jacs[0] = jac;
conditioned_cost_function.Evaluate(parameters, result, jacs);
for (int i = 0; i < kTestCostFunctionSize; i++) {
EXPECT_DOUBLE_EQ((i + 2) * (v1[i] - v2[i]) + i * 7, result[i]);
}
for (int i = 0; i < kTestCostFunctionSize; i++) {
for (int j = 0; j < kTestCostFunctionSize; j++) {
double actual = jac[i * kTestCostFunctionSize + j];
if (i != j) {
EXPECT_DOUBLE_EQ(0, actual);
} else {
EXPECT_DOUBLE_EQ(i + 2, actual);
}
}
}
}
TEST(ConditionedCostFunction, SharedConditionersDoNotTriggerDoubleFree) {
// Make a cost function that computes x - v2
double v2[kTestCostFunctionSize];
VectorRef v2_vector(v2, kTestCostFunctionSize, 1);
Matrix identity = Matrix::Identity(kTestCostFunctionSize, kTestCostFunctionSize);
NormalPrior* difference_cost_function = new NormalPrior(identity, v2_vector);
CostFunction* conditioner = new LinearCostFunction(2, 7);
std::vector<CostFunction*> conditioners;
for (int i = 0; i < kTestCostFunctionSize; i++) {
conditioners.push_back(conditioner);
}
ConditionedCostFunction conditioned_cost_function(
difference_cost_function, conditioners, TAKE_OWNERSHIP);
}
} // namespace internal
} // namespace ceres
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: wjr@google.com (William Rucklidge)
//
// This file contains the implementation of the conditioned cost function.
#include "ceres/conditioned_cost_function.h"
#include <cstddef>
#include "ceres/internal/eigen.h"
#include "ceres/stl_util.h"
#include "ceres/types.h"
#include "glog/logging.h"
namespace ceres {
// This cost function has the same dimensions (parameters, residuals) as
// the one it's wrapping.
ConditionedCostFunction::ConditionedCostFunction(
CostFunction* wrapped_cost_function,
const std::vector<CostFunction*>& conditioners,
Ownership ownership)
: wrapped_cost_function_(wrapped_cost_function),
conditioners_(conditioners),
ownership_(ownership) {
// Set up our dimensions.
set_num_residuals(wrapped_cost_function_->num_residuals());
*mutable_parameter_block_sizes() =
wrapped_cost_function_->parameter_block_sizes();
// Sanity-check the conditioners' dimensions.
CHECK_EQ(wrapped_cost_function_->num_residuals(), conditioners_.size());
for (int i = 0; i < wrapped_cost_function_->num_residuals(); i++) {
if (conditioners[i]) {
CHECK_EQ(1, conditioners[i]->num_residuals());
CHECK_EQ(1, conditioners[i]->parameter_block_sizes().size());
CHECK_EQ(1, conditioners[i]->parameter_block_sizes()[0]);
}
}
}
ConditionedCostFunction::~ConditionedCostFunction() {
if (ownership_ == TAKE_OWNERSHIP) {
STLDeleteUniqueContainerPointers(conditioners_.begin(), conditioners_.end());
} else {
wrapped_cost_function_.release();
}
}
bool ConditionedCostFunction::Evaluate(double const* const* parameters,
double* residuals,
double** jacobians) const {
bool success = wrapped_cost_function_->Evaluate(parameters, residuals,
jacobians);
if (!success) {
return false;
}
for (int r = 0; r < wrapped_cost_function_->num_residuals(); r++) {
// On output, we want to have
// residuals[r] = conditioners[r](wrapped_residuals[r])
// For parameter block i, column c,
// jacobians[i][r*parameter_block_size_[i] + c] =
// = d residual[r] / d parameters[i][c]
// = conditioners[r]'(wrapped_residuals[r]) *
// d wrapped_residuals[r] / d parameters[i][c]
if (conditioners_[r]) {
double conditioner_derivative;
double* conditioner_derivative_pointer = &conditioner_derivative;
double** conditioner_derivative_pointer2 =
&conditioner_derivative_pointer;
if (!jacobians) {
conditioner_derivative_pointer2 = NULL;
}
double unconditioned_residual = residuals[r];
double* parameter_pointer = &unconditioned_residual;
success = conditioners_[r]->Evaluate(¶meter_pointer,
&residuals[r],
conditioner_derivative_pointer2);
if (!success) {
return false;
}
if (jacobians) {
for (int i = 0;
i < wrapped_cost_function_->parameter_block_sizes().size();
i++) {
if (jacobians[i]) {
int parameter_block_size =
wrapped_cost_function_->parameter_block_sizes()[i];
VectorRef jacobian_row(jacobians[i] + r * parameter_block_size,
parameter_block_size, 1);
jacobian_row *= conditioner_derivative;
}
}
}
}
}
return true;
}
} // namespace ceres