7#include <Eigen/SparseCore>
9#include "sleipnir/autodiff/adjoint_expression_graph.hpp"
10#include "sleipnir/autodiff/variable.hpp"
11#include "sleipnir/autodiff/variable_matrix.hpp"
12#include "sleipnir/util/concepts.hpp"
13#include "sleipnir/util/small_vector.hpp"
14#include "sleipnir/util/symbol_exports.hpp"
28 requires(UpLo == Eigen::Lower) || (UpLo == (Eigen::Lower | Eigen::Upper))
52 for (
size_t col = 0; col < m_wrt.size(); ++col) {
53 m_wrt[col].expr->
col = col;
56 for (
auto& variable : m_variables) {
57 m_graphs.emplace_back(variable);
61 for (
auto& node : m_wrt) {
65 for (
int row = 0; row < m_variables.rows(); ++row) {
66 if (m_variables[row].expr ==
nullptr) {
70 if (m_variables[row].type() == ExpressionType::LINEAR) {
74 m_graphs[row].append_adjoint_triplets(m_cached_triplets, row, m_wrt);
75 }
else if (m_variables[row].type() > ExpressionType::LINEAR) {
78 m_nonlinear_rows.emplace_back(row);
82 if (m_nonlinear_rows.empty()) {
83 m_H.setFromTriplets(m_cached_triplets.begin(), m_cached_triplets.end());
84 if constexpr (UpLo == Eigen::Lower) {
85 m_H = m_H.triangularView<Eigen::Lower>();
102 for (
int row = 0; row < m_variables.rows(); ++row) {
103 auto grad = m_graphs[row].generate_gradient_tree(m_wrt);
104 for (
int col = 0; col < m_wrt.rows(); ++col) {
105 if (grad[col].expr !=
nullptr) {
106 result[row, col] = std::move(grad[col]);
121 const Eigen::SparseMatrix<double>&
value() {
122 if (m_nonlinear_rows.empty()) {
126 for (
auto& graph : m_graphs) {
127 graph.update_values();
132 auto triplets = m_cached_triplets;
135 for (
int row : m_nonlinear_rows) {
136 m_graphs[row].append_adjoint_triplets(triplets, row, m_wrt);
139 if (!triplets.empty()) {
140 m_H.setFromTriplets(triplets.begin(), triplets.end());
141 if constexpr (UpLo == Eigen::Lower) {
142 m_H = m_H.triangularView<Eigen::Lower>();
157 small_vector<detail::AdjointExpressionGraph> m_graphs;
159 Eigen::SparseMatrix<double> m_H{m_variables.
rows(), m_wrt.
rows()};
162 small_vector<Eigen::Triplet<double>> m_cached_triplets;
166 small_vector<int> m_nonlinear_rows;
Definition hessian.hpp:29
Hessian(Variable variable, SleipnirMatrixLike auto wrt) noexcept
Definition hessian.hpp:47
Hessian(Variable variable, Variable wrt) noexcept
Definition hessian.hpp:37
VariableMatrix get() const
Definition hessian.hpp:98
const Eigen::SparseMatrix< double > & value()
Definition hessian.hpp:121
Definition variable_matrix.hpp:29
int rows() const
Definition variable_matrix.hpp:951
VariableBlock< VariableMatrix > col(int col)
Definition variable_matrix.hpp:546
static constexpr empty_t empty
Definition variable_matrix.hpp:39
Definition variable.hpp:40
Definition adjoint_expression_graph.hpp:21
VariableMatrix generate_gradient_tree(const VariableMatrix &wrt) const
Definition adjoint_expression_graph.hpp:52
Definition concepts.hpp:30