MCPcopy Create free account
hub / github.com/PatWie/CppNumericalSolvers / AddExpression

Class AddExpression

include/cppoptlib/function_expressions.h:93–143  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

91template <typename F, typename G,
92 DifferentiabilityMode TMode = MinDifferentiability<F, G>::value>
93struct AddExpression
94 : public FunctionInterface<typename F::ScalarType, TMode, F::Dimension> {
95 static_assert(
96 F::Dimension == G::Dimension,
97 "Compile-time dimension mismatch: F and G must have the same dimension.");
98 static_assert(
99 std::is_same<typename F::ScalarType, typename G::ScalarType>::value,
100 "Compile-time scalar-type mismatch: F and G must have the same scalar "
101 "type.");
102
103 static constexpr int Dimension = F::Dimension;
104 using ScalarType = typename F::ScalarType;
105 using VectorType = Eigen::Matrix<ScalarType, Dimension, 1>;
106 using MatrixType = Eigen::Matrix<ScalarType, Dimension, Dimension>;
107 static constexpr DifferentiabilityMode Differentiability = TMode;
108
109 F f;
110 G g;
111 AddExpression(const F& f_, const G& g_) : f(f_), g(g_) {}
112 virtual ScalarType operator()(
113 const VectorType& x, [[maybe_unused]] VectorType* grad = nullptr,
114 [[maybe_unused]] MatrixType* hess = nullptr) const override {
115 if constexpr (TMode == DifferentiabilityMode::None) {
116 return f(x) + g(x);
117 } else if constexpr (TMode == DifferentiabilityMode::First) {
118 VectorType grad_f(x.size()), grad_g(x.size());
119 ScalarType fx_f = f(x, &grad_f);
120 ScalarType fx_g = g(x, &grad_g);
121 if (grad) {
122 *grad = grad_f + grad_g;
123 }
124 return fx_f + fx_g;
125 } else { // Second
126 VectorType grad_f(x.size()), grad_g(x.size());
127 MatrixType hess_f(x.size(), x.size()), hess_g(x.size(), x.size());
128 ScalarType fx_f = f(x, &grad_f, &hess_f);
129 ScalarType fx_g = g(x, &grad_g, &hess_g);
130 if (grad) {
131 *grad = grad_f + grad_g;
132 }
133 if (hess) {
134 *hess = hess_f + hess_g;
135 }
136 return fx_f + fx_g;
137 }
138 }
139 virtual std::unique_ptr<FunctionInterface<ScalarType, TMode, Dimension>>
140 clone() const override {
141 return std::make_unique<AddExpression<F, G, TMode>>(f, g);
142 }
143};
144
145// Subtraction Expression.
146template <typename F, typename G,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected