9#include <Eigen/SparseCore>
10#include <gch/small_vector.hpp>
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"
33template <
typename Scalar,
int UpLo>
34 requires(UpLo == Eigen::Lower) || (UpLo == (Eigen::Lower | Eigen::Upper))
50 : m_variables{detail::gradient_tree(
53 slp_assert(m_wrt.cols() == 1);
56 m_top_lists.emplace_back(detail::topological_sort(
variable.expr));
60 for (
size_t col = 0; col < m_wrt.size(); ++col) {
61 m_wrt[col].expr->scratch = col;
66 m_output_lists.emplace_back();
68 if (
node->scratch != -1) {
69 m_output_lists.back().emplace_back(
node->scratch,
node);
75 for (
auto&
node : m_wrt) {
76 node.expr->scratch = -1;
79 for (
int row = 0; row < m_variables.rows(); ++row) {
80 if (m_variables[row].expr ==
nullptr) {
84 if (detail::has_constant_gradient(m_top_lists[row])) {
87 detail::append_triplets(m_top_lists[row], m_output_lists[row],
88 m_cached_triplets, row);
91 m_nonlinear_rows.emplace_back(row);
95 if (m_nonlinear_rows.empty()) {
96 m_H.setFromTriplets(m_cached_triplets.begin(), m_cached_triplets.end());
97 if constexpr (
UpLo == Eigen::Lower) {
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]);
130 const Eigen::SparseMatrix<Scalar>&
value() {
131 if (m_nonlinear_rows.empty()) {
135 for (
auto&
top_list : m_top_lists) {
144 for (
int row : m_nonlinear_rows) {
145 detail::append_triplets(m_top_lists[row], m_output_lists[row],
triplets,
150 if constexpr (
UpLo == Eigen::Lower) {
162 gch::small_vector<detail::ExpressionGraph<Scalar>> m_top_lists;
166 gch::small_vector<std::pair<int, detail::Expression<Scalar>*>>>
169 Eigen::SparseMatrix<Scalar> m_H{m_variables.rows(), m_wrt.rows()};
172 gch::small_vector<Eigen::Triplet<Scalar>> m_cached_triplets;
176 gch::small_vector<int> m_nonlinear_rows;
180extern template class EXPORT_TEMPLATE_DECLARE(SLEIPNIR_DLLEXPORT)
181Hessian<double, Eigen::Lower | Eigen::Upper>;
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