Sleipnir C++ API
Loading...
Searching...
No Matches
expression_graph.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <ranges>
6#include <utility>
7
8#include <Eigen/SparseCore>
9#include <gch/small_vector.hpp>
10
11#include "sleipnir/autodiff/expression.hpp"
12#include "sleipnir/autodiff/expression_type.hpp"
13
14namespace slp::detail {
15
19template <typename Scalar>
20using ExpressionGraph = gch::small_vector<Expression<Scalar>*>;
21
28template <typename Scalar>
29ExpressionGraph<Scalar> topological_sort(const ExpressionPtr<Scalar>& root) {
30 ExpressionGraph<Scalar> list;
31
32 // If the root type is constant, updates are a no-op, so return an empty list
33 if (root == nullptr || root->type() == ExpressionType::CONSTANT) {
34 return list;
35 }
36
37 // Stack of nodes to explore
38 gch::small_vector<Expression<Scalar>*> stack;
39
40 // Enumerate incoming edges for each node via depth-first search
41 //
42 // NOTE: scratch counts incoming edges, offset by -1 so -1 means no edges.
43 stack.emplace_back(root.get());
44 while (!stack.empty()) {
45 auto node = stack.back();
46 stack.pop_back();
47
48 node->visit_args([&stack](const auto& arg) {
49 // If the node hasn't been explored yet, add it to the stack
50 if (++arg->scratch == 0) {
51 stack.push_back(arg);
52 }
53 });
54 }
55
56 // Generate topological sort of graph from parent to child.
57 //
58 // A node is only added to the stack after all its incoming edges have been
59 // traversed. Expression::scratch is a decrementing counter for tracking this.
60 //
61 // https://en.wikipedia.org/wiki/Topological_sorting
62 stack.emplace_back(root.get());
63 while (!stack.empty()) {
64 auto node = stack.back();
65 stack.pop_back();
66
67 list.emplace_back(node);
68
69 node->visit_args([&stack](const auto& arg) {
70 // If we traversed all this node's incoming edges, add it to the stack
71 if (--arg->scratch == -1) {
72 stack.push_back(arg);
73 }
74 });
75 }
76
77 return list;
78}
79
85template <typename Scalar>
86bool has_constant_gradient(const ExpressionGraph<Scalar>& list) {
87 using enum ExpressionType;
88
89 // The gradient of a constant or parameter expression is zero
90 if (list.empty() || list[0]->type() < LINEAR) {
91 return true;
92 }
93
94 // The gradient of a quadratic or nonlinear expression is never constant
95 if (list[0]->type() > LINEAR) {
96 return false;
97 }
98
99 for (const auto& node : list) {
100 // The gradient of a linear expression is composed of the partial
101 // derivatives of its linear operators, so only the ones that vary with
102 // their operator's arguments can change it. Operators on only constants
103 // and parameters (e.g., p₁ * p₂ in x + p₁ * p₂) are skipped because their
104 // partial derivatives are with respect to parameters, which aren't in the
105 // gradient.
106 if (node->type() == LINEAR && !node->has_constant_partials()) {
107 // A linear operator's partial derivatives can't depend on decision
108 // variables, or the operator wouldn't be linear, so they depend only on
109 // its constant and parameter arguments
110 bool has_parameter_arg = false;
111 node->visit_args([&](const auto& arg) {
112 has_parameter_arg |= arg->type() == PARAMETER;
113 });
114
115 // A parameter's value can change between solves
116 if (has_parameter_arg) {
117 return false;
118 }
119 }
120 }
121
122 return true;
123}
124
130template <typename Scalar>
131void update_values(const ExpressionGraph<Scalar>& list) {
132 // Traverse graph from child to parent and update values
133 for (auto& node : list | std::views::reverse) {
134 // Leaf nodes don't need updating
135 if (!node->is_leaf) {
136 node->val = node->value();
137 }
138 }
139}
140
149template <typename Scalar>
150void append_triplets(
151 const ExpressionGraph<Scalar>& top_list,
152 const gch::small_vector<std::pair<int, detail::Expression<Scalar>*>>&
153 output_list,
154 gch::small_vector<Eigen::Triplet<Scalar>>& triplets, int row) {
155 // Read docs/algorithms.md#Reverse_accumulation_automatic_differentiation
156 // for background on reverse accumulation automatic differentiation.
157
158 if (top_list.empty()) {
159 return;
160 }
161
162 // Set root node's adjoint to 1 since df/df is 1
163 top_list[0]->adj = Scalar(1);
164
165 // Zero the rest of the adjoints
166 for (auto& node : top_list | std::views::drop(1)) {
167 node->adj = Scalar(0);
168 }
169
170 // df/dx = (df/dy)(dy/dx). The adjoint of x is equal to the adjoint of y
171 // multiplied by dy/dx. If there are multiple "paths" from the root node to
172 // variable; the variable's adjoint is the sum of each path's adjoint
173 // contribution.
174 for (const auto& node : top_list) {
175 // Leaf nodes have no children to propagate adjoints to
176 if (!node->is_leaf) {
177 node->accumulate_adjoints();
178 }
179 }
180
181 // Exploit the row's sparsity pattern by only appending wrt adjoints that
182 // appear in the expression graph
183 for (const auto& [col, node] : output_list) {
184 // Append adjoints of wrt to sparse matrix triplets
185 triplets.emplace_back(row, col, node->adj);
186 }
187}
188
189} // namespace slp::detail