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/expression_type.hpp"
15#include "sleipnir/autodiff/variable.hpp"
16#include "sleipnir/autodiff/variable_matrix.hpp"
17#include "sleipnir/util/assert.hpp"
18#include "sleipnir/util/concepts.hpp"
19#include "sleipnir/util/empty.hpp"
20#include "sleipnir/util/symbol_exports.hpp"
21
22namespace slp {
23
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 (m_variables[row].type() == ExpressionType::LINEAR) {
85 // If the row is linear, compute its gradient once here and cache its
86 // triplets. Constant rows are ignored because their gradients have no
87 // nonzero triplets.
88 detail::append_triplets(m_top_lists[row], m_output_lists[row],
89 m_cached_triplets, row);
90 } else if (m_variables[row].type() > ExpressionType::LINEAR) {
91 // If the row is quadratic or nonlinear, add it to the list of nonlinear
92 // rows to be recomputed in value().
93 m_nonlinear_rows.emplace_back(row);
94 }
95 }
96
97 if (m_nonlinear_rows.empty()) {
98 m_H.setFromTriplets(m_cached_triplets.begin(), m_cached_triplets.end());
99 if constexpr (UpLo == Eigen::Lower) {
100 m_H = m_H.template triangularView<Eigen::Lower>();
101 }
102 }
103 }
104
112 VariableMatrix<Scalar> result{detail::empty, m_variables.rows(),
113 m_wrt.rows()};
114
115 for (int row = 0; row < m_variables.rows(); ++row) {
116 auto grad = detail::gradient_tree(m_top_lists[row], m_wrt);
117 for (int col = 0; col < m_wrt.rows(); ++col) {
118 if (grad[col].expr != nullptr) {
119 result[row, col] = std::move(grad[col]);
120 } else {
121 result[row, col] = Variable{Scalar(0)};
122 }
123 }
124 }
125
126 return result;
127 }
128
132 const Eigen::SparseMatrix<Scalar>& value() {
133 if (m_nonlinear_rows.empty()) {
134 return m_H;
135 }
136
137 for (auto& top_list : m_top_lists) {
138 detail::update_values(top_list);
139 }
140
141 // Copy the cached triplets so triplets added for the nonlinear rows are
142 // thrown away at the end of the function
143 auto triplets = m_cached_triplets;
144
145 // Compute each nonlinear row of the Hessian
146 for (int row : m_nonlinear_rows) {
147 detail::append_triplets(m_top_lists[row], m_output_lists[row], triplets,
148 row);
149 }
150
151 m_H.setFromTriplets(triplets.begin(), triplets.end());
152 if constexpr (UpLo == Eigen::Lower) {
153 m_H = m_H.template triangularView<Eigen::Lower>();
154 }
155
156 return m_H;
157 }
158
159 private:
160 VariableMatrix<Scalar> m_variables;
162
164 gch::small_vector<detail::ExpressionGraph<Scalar>> m_top_lists;
165
167 gch::small_vector<
168 gch::small_vector<std::pair<int, detail::Expression<Scalar>*>>>
169 m_output_lists;
170
171 Eigen::SparseMatrix<Scalar> m_H{m_variables.rows(), m_wrt.rows()};
172
173 // Cached triplets for gradients of linear rows
174 gch::small_vector<Eigen::Triplet<Scalar>> m_cached_triplets;
175
176 // List of row indices for nonlinear rows whose graients will be computed in
177 // value()
178 gch::small_vector<int> m_nonlinear_rows;
179};
180
181// @cond Suppress Doxygen
182extern template class EXPORT_TEMPLATE_DECLARE(SLEIPNIR_DLLEXPORT)
183Hessian<double, Eigen::Lower | Eigen::Upper>;
184// @endcond
185
186} // namespace slp
Definition hessian.hpp:35
VariableMatrix< Scalar > get() const
Definition hessian.hpp:111
const Eigen::SparseMatrix< Scalar > & value()
Definition hessian.hpp:132
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:35
Definition variable.hpp:55
Definition concepts.hpp:33