WPILibC++ 2027.0.0-alpha-4
Loading...
Searching...
No Matches
gradient.hpp
Go to the documentation of this file.
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <utility>
6
7#include <Eigen/SparseCore>
8
14
15namespace slp {
16
17/// This class calculates the gradient of a variable with respect to a vector of
18/// variables.
19///
20/// The gradient is only recomputed if the variable expression is quadratic or
21/// higher order.
22///
23/// @tparam Scalar Scalar type.
24template <typename Scalar>
25class Gradient {
26 public:
27 /// Constructs a Gradient object.
28 ///
29 /// @param variable Variable of which to compute the gradient.
30 /// @param wrt Variable with respect to which to compute the gradient.
32 : m_jacobian{std::move(variable), std::move(wrt)} {}
33
34 /// Constructs a Gradient object.
35 ///
36 /// @param variable Variable of which to compute the gradient.
37 /// @param wrt Vector of variables with respect to which to compute the
38 /// gradient.
40 : m_jacobian{VariableMatrix{std::move(variable)}, std::move(wrt)} {}
41
42 /// Returns the gradient as a VariableMatrix.
43 ///
44 /// This is useful when constructing optimization problems with derivatives in
45 /// them.
46 ///
47 /// @return The gradient as a VariableMatrix.
48 VariableMatrix<Scalar> get() const { return m_jacobian.get().T(); }
49
50 /// Evaluates the gradient at wrt's value.
51 ///
52 /// @return The gradient at wrt's value.
53 const Eigen::SparseVector<Scalar>& value() {
54 m_g = m_jacobian.value().transpose();
55
56 return m_g;
57 }
58
59 private:
60 Eigen::SparseVector<Scalar> m_g;
61
62 Jacobian<Scalar> m_jacobian;
63};
64
66Gradient<double>;
67
68} // namespace slp
#define EXPORT_TEMPLATE_DECLARE(export)
Definition SymbolExports.hpp:94
const Eigen::SparseVector< Scalar > & value()
Evaluates the gradient at wrt's value.
Definition gradient.hpp:53
Gradient(Variable< Scalar > variable, SleipnirMatrixLike< Scalar > auto wrt)
Constructs a Gradient object.
Definition gradient.hpp:39
VariableMatrix< Scalar > get() const
Returns the gradient as a VariableMatrix.
Definition gradient.hpp:48
Gradient(Variable< Scalar > variable, Variable< Scalar > wrt)
Constructs a Gradient object.
Definition gradient.hpp:31
This class calculates the Jacobian of a vector of variables with respect to a vector of variables.
Definition jacobian.hpp:28
An autodiff variable pointing to an expression node.
Definition variable.hpp:47
A matrix of autodiff variables.
Definition variable_matrix.hpp:33
VariableMatrix< Scalar > T() const
Returns the transpose of the variable matrix.
Definition variable_matrix.hpp:957
Definition concepts.hpp:33
Definition expression_graph.hpp:11
Definition StringMap.hpp:773
#define SLEIPNIR_DLLEXPORT
Definition symbol_exports.hpp:34