Sleipnir C++ API
Loading...
Searching...
No Matches
hessian.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <cstddef>
6#include <utility>
7
8#include <Eigen/Core>
9#include <Eigen/SparseCore>
10#include <gch/small_vector.hpp>
11
12#include "sleipnir/autodiff/expression.hpp"
13#include "sleipnir/autodiff/expression_graph.hpp"
14#include "sleipnir/autodiff/variable.hpp"
15#include "sleipnir/autodiff/variable_matrix.hpp"
16#include "sleipnir/util/assert.hpp"
17#include "sleipnir/util/concepts.hpp"
18#include "sleipnir/util/empty.hpp"
19#include "sleipnir/util/symbol_exports.hpp"
20
21namespace slp {
22
33template <typename Scalar, int UpLo>
34 requires(UpLo == Eigen::Lower) || (UpLo == (Eigen::Lower | Eigen::Upper))
35class Hessian {
36 public:
43
50 : m_variables{detail::gradient_tree(
51 detail::topological_sort(variable.expr), wrt)},
52 m_wrt{std::move(wrt)} {
53 slp_assert(m_wrt.cols() == 1);
54
55 for (auto& variable : m_variables) {
56 m_top_lists.emplace_back(detail::topological_sort(variable.expr));
57 }
58
59 // Initialize column each expression's adjoint occupies in the Jacobian
60 for (size_t col = 0; col < m_wrt.size(); ++col) {
61 m_wrt[col].expr->scratch = col;
62 }
63
64 // Make list of only nodes in output row, and their output columns
65 for (auto& top_list : m_top_lists) {
66 m_output_lists.emplace_back();
67 for (const auto& node : top_list) {
68 if (node->scratch != -1) {
69 m_output_lists.back().emplace_back(node->scratch, node);
70 }
71 }
72 }
73
74 // Reset col to -1
75 for (auto& node : m_wrt) {
76 node.expr->scratch = -1;
77 }
78
79 for (int row = 0; row < m_variables.rows(); ++row) {
80 if (m_variables[row].expr == nullptr) {
81 continue;
82 }
83
84 if (detail::has_constant_gradient(m_top_lists[row])) {
85 // If the row's gradient is constant, compute it once here and cache
86 // its triplets
87 detail::append_triplets(m_top_lists[row], m_output_lists[row],
88 m_cached_triplets, row);
89 } else {
90 // Otherwise, add it to the list of rows to be recomputed in value()
91 m_nonlinear_rows.emplace_back(row);
92 }
93 }
94
95 if (m_nonlinear_rows.empty()) {
96 m_H.setFromTriplets(m_cached_triplets.begin(), m_cached_triplets.end());
97 if constexpr (UpLo == Eigen::Lower) {
98 m_H = m_H.template triangularView<Eigen::Lower>();
99 }
100 }
101 }
102
110 VariableMatrix<Scalar> result{detail::empty, m_variables.rows(),
111 m_wrt.rows()};
112
113 for (int row = 0; row < m_variables.rows(); ++row) {
114 auto grad = detail::gradient_tree(m_top_lists[row], m_wrt);
115 for (int col = 0; col < m_wrt.rows(); ++col) {
116 if (grad[col].expr != nullptr) {
117 result[row, col] = std::move(grad[col]);
118 } else {
119 result[row, col] = Variable{Scalar(0)};
120 }
121 }
122 }
123
124 return result;
125 }
126
130 const Eigen::SparseMatrix<Scalar>& value() {
131 if (m_nonlinear_rows.empty()) {
132 return m_H;
133 }
134
135 for (auto& top_list : m_top_lists) {
136 detail::update_values(top_list);
137 }
138
139 // Copy the cached triplets so triplets added for the nonlinear rows are
140 // thrown away at the end of the function
141 auto triplets = m_cached_triplets;
142
143 // Compute each nonlinear row of the Hessian
144 for (int row : m_nonlinear_rows) {
145 detail::append_triplets(m_top_lists[row], m_output_lists[row], triplets,
146 row);
147 }
148
149 m_H.setFromTriplets(triplets.begin(), triplets.end());
150 if constexpr (UpLo == Eigen::Lower) {
151 m_H = m_H.template triangularView<Eigen::Lower>();
152 }
153
154 return m_H;
155 }
156
157 private:
158 VariableMatrix<Scalar> m_variables;
160
162 gch::small_vector<detail::ExpressionGraph<Scalar>> m_top_lists;
163
165 gch::small_vector<
166 gch::small_vector<std::pair<int, detail::Expression<Scalar>*>>>
167 m_output_lists;
168
169 Eigen::SparseMatrix<Scalar> m_H{m_variables.rows(), m_wrt.rows()};
170
171 // Cached triplets for gradients of linear rows
172 gch::small_vector<Eigen::Triplet<Scalar>> m_cached_triplets;
173
174 // List of row indices for nonlinear rows and linear rows with parameters
175 // whose gradients will be computed in value()
176 gch::small_vector<int> m_nonlinear_rows;
177};
178
179// @cond Suppress Doxygen
180extern template class EXPORT_TEMPLATE_DECLARE(SLEIPNIR_DLLEXPORT)
181Hessian<double, Eigen::Lower | Eigen::Upper>;
182// @endcond
183
184} // namespace slp
Definition hessian.hpp:35
VariableMatrix< Scalar > get() const
Definition hessian.hpp:109
const Eigen::SparseMatrix< Scalar > & value()
Definition hessian.hpp:130
Hessian(Variable< Scalar > variable, SleipnirMatrixLike< Scalar > auto wrt)
Definition hessian.hpp:49
Hessian(Variable< Scalar > variable, Variable< Scalar > wrt)
Definition hessian.hpp:41
Definition intrusive_shared_ptr.hpp:27
Definition variable_matrix.hpp:38
Definition variable.hpp:63
Definition concepts.hpp:33