7#include <Eigen/SparseCore>
8#include <gch/small_vector.hpp>
10#include "sleipnir/autodiff/expression_graph.hpp"
11#include "sleipnir/autodiff/variable.hpp"
12#include "sleipnir/autodiff/variable_matrix.hpp"
13#include "sleipnir/util/assert.hpp"
14#include "sleipnir/util/concepts.hpp"
15#include "sleipnir/util/symbol_exports.hpp"
28template <
typename Scalar,
int UpLo>
29 requires(UpLo == Eigen::Lower) || (UpLo == (Eigen::Lower | Eigen::Upper))
45 : m_variables{detail::gradient_tree(
48 slp_assert(
wrt.cols() == 1);
51 m_top_lists.emplace_back(detail::topological_sort(
variable.expr));
55 for (
size_t col = 0; col < m_wrt.size(); ++col) {
56 m_wrt[col].expr->scratch = col;
61 m_output_lists.emplace_back();
63 if (
node->scratch != -1) {
64 m_output_lists.back().emplace_back(
node->scratch,
node);
70 for (
auto&
node : m_wrt) {
71 node.expr->scratch = -1;
74 for (
int row = 0; row < m_variables.rows(); ++row) {
75 if (m_variables[row].expr ==
nullptr) {
79 if (m_variables[row].type() == ExpressionType::LINEAR) {
83 detail::append_triplets(m_top_lists[row], m_output_lists[row],
84 m_cached_triplets, row);
85 }
else if (m_variables[row].type() > ExpressionType::LINEAR) {
88 m_nonlinear_rows.emplace_back(row);
92 if (m_nonlinear_rows.empty()) {
93 m_H.setFromTriplets(m_cached_triplets.begin(), m_cached_triplets.end());
94 if constexpr (
UpLo == Eigen::Lower) {
110 for (
int row = 0; row < m_variables.rows(); ++row) {
111 auto grad = detail::gradient_tree(m_top_lists[row], m_wrt);
112 for (
int col = 0; col < m_wrt.rows(); ++col) {
113 if (
grad[col].expr !=
nullptr) {
127 const Eigen::SparseMatrix<Scalar>&
value() {
128 if (m_nonlinear_rows.empty()) {
132 for (
auto&
top_list : m_top_lists) {
141 for (
int row : m_nonlinear_rows) {
142 detail::append_triplets(m_top_lists[row], m_output_lists[row],
triplets,
147 if constexpr (
UpLo == Eigen::Lower) {
159 gch::small_vector<detail::ExpressionGraph<Scalar>> m_top_lists;
163 gch::small_vector<std::pair<int, detail::Expression<Scalar>*>>>
166 Eigen::SparseMatrix<Scalar> m_H{m_variables.rows(), m_wrt.rows()};
169 gch::small_vector<Eigen::Triplet<Scalar>> m_cached_triplets;
173 gch::small_vector<int> m_nonlinear_rows;
177extern template class EXPORT_TEMPLATE_DECLARE(SLEIPNIR_DLLEXPORT)
178Hessian<double, Eigen::Lower | Eigen::Upper>;
Definition hessian.hpp:30
VariableMatrix< Scalar > get() const
Definition hessian.hpp:106
const Eigen::SparseMatrix< Scalar > & value()
Definition hessian.hpp:127
Hessian(Variable< Scalar > variable, SleipnirMatrixLike< Scalar > auto wrt)
Definition hessian.hpp:44
Hessian(Variable< Scalar > variable, Variable< Scalar > wrt)
Definition hessian.hpp:36
Definition intrusive_shared_ptr.hpp:27
Definition variable_matrix.hpp:33
Definition variable.hpp:52
Definition concepts.hpp:33