8 #ifndef INCLUDE_TEMPLE_OPTIMIZATION_COMMON_H
9 #define INCLUDE_TEMPLE_OPTIMIZATION_COMMON_H
14 namespace Molassembler {
18 namespace Optimization {
20 template<
typename FloatType>
23 std::is_floating_point<FloatType>::value,
24 "This struct is not intended for anything else but floats"
32 return std::fabs(proposed - current);
35 void propagate() { current = proposed; }
38 template<
typename EigenType>
43 typename EigenType::Scalar deltaNorm()
const {
44 return (proposed - current).norm();
54 std::swap(current, proposed);
58 template<
typename FloatType,
typename VectorType,
typename UpdateFunction>
60 UpdateFunction
function;
65 const VectorType& parameters,
67 Eigen::Ref<VectorType> gradient
69 function(parameters, value, gradient);
75 template<
typename VectorType,
typename UpdateFunction>
76 auto negateFunction(UpdateFunction&& fn) {
77 using FloatType =
typename VectorType::Scalar;
81 template<
typename Function,
typename FloatType>
82 auto numericalGradient(
84 const Eigen::Matrix<FloatType, Eigen::Dynamic, 1>& parameters
86 using VectorType = Eigen::Matrix<FloatType, Eigen::Dynamic, 1>;
87 const unsigned P = parameters.size();
88 VectorType numericalGradient(P);
89 VectorType diffParameters = parameters;
92 constexpr FloatType h = 1e-4;
95 for(
unsigned i = 0; i < P; ++i) {
96 diffParameters(i) += h;
97 b =
function(diffParameters);
98 diffParameters(i) -= 2 * h;
99 a =
function(diffParameters);
100 diffParameters(i) = parameters(i);
101 numericalGradient(i) = (b - a) / (2 * h);
104 return numericalGradient;
107 template<
typename Function,
typename FloatType>
108 auto numericalHessian(
110 const Eigen::Matrix<FloatType, Eigen::Dynamic, 1>& parameters
112 using VectorType = Eigen::Matrix<FloatType, Eigen::Dynamic, 1>;
113 using MatrixType = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic>;
114 const unsigned P = parameters.size();
115 MatrixType numericalHessian(P, P);
116 VectorType diffParameters = parameters;
119 constexpr FloatType h = 1e-4;
124 for(
unsigned i = 0; i < P; ++i) {
126 b =
function(diffParameters);
127 diffParameters(i) += h;
128 c =
function(diffParameters);
129 diffParameters(i) -= 2 * h;
130 a =
function(diffParameters);
131 diffParameters(i) = parameters(i);
132 numericalHessian(i, i) = (a - 2 * b + c) / (h * h);
135 for(
unsigned j = i + 1; j < P; ++j) {
137 diffParameters(i) += h;
138 diffParameters(j) += h;
139 a =
function(diffParameters);
141 diffParameters(j) -= 2 * h;
142 b =
function(diffParameters);
144 diffParameters(i) -= 2 * h;
145 d =
function(diffParameters);
147 diffParameters(j) += 2 * h;
148 c =
function(diffParameters);
150 numericalHessian(i, j) = (a - b - c + d) / (4 * h * h);
151 numericalHessian(j, i) = numericalHessian(i, j);
155 return numericalHessian;
FloatType absDelta() const
Returns signed difference: proposed - current.
Definition: Common.h:31