8#include <Eigen/SparseCore>
9#include <gch/small_vector.hpp>
11#include "sleipnir/autodiff/expression.hpp"
12#include "sleipnir/autodiff/expression_type.hpp"
14namespace slp::detail {
19template <
typename Scalar>
20using ExpressionGraph = gch::small_vector<Expression<Scalar>*>;
28template <
typename Scalar>
29ExpressionGraph<Scalar> topological_sort(
const ExpressionPtr<Scalar>& root) {
30 ExpressionGraph<Scalar> list;
33 if (root ==
nullptr || root->type() == ExpressionType::CONSTANT) {
38 gch::small_vector<Expression<Scalar>*> stack;
43 stack.emplace_back(root.get());
44 while (!stack.empty()) {
45 auto node = stack.back();
48 node->visit_args([&stack](
const auto& arg) {
50 if (++arg->scratch == 0) {
62 stack.emplace_back(root.get());
63 while (!stack.empty()) {
64 auto node = stack.back();
67 list.emplace_back(node);
69 node->visit_args([&stack](
const auto& arg) {
71 if (--arg->scratch == -1) {
85template <
typename Scalar>
86bool has_constant_gradient(
const ExpressionGraph<Scalar>& list) {
87 using enum ExpressionType;
90 if (list.empty() || list[0]->type() < LINEAR) {
95 if (list[0]->type() > LINEAR) {
99 for (
const auto& node : list) {
106 if (node->type() == LINEAR && !node->has_constant_partials()) {
110 bool has_parameter_arg =
false;
111 node->visit_args([&](
const auto& arg) {
112 has_parameter_arg |= arg->type() == PARAMETER;
116 if (has_parameter_arg) {
130template <
typename Scalar>
131void update_values(
const ExpressionGraph<Scalar>& list) {
133 for (
auto& node : list | std::views::reverse) {
135 if (!node->is_leaf) {
136 node->val = node->value();
149template <
typename Scalar>
151 const ExpressionGraph<Scalar>& top_list,
152 const gch::small_vector<std::pair<
int, detail::Expression<Scalar>*>>&
154 gch::small_vector<Eigen::Triplet<Scalar>>& triplets,
int row) {
158 if (top_list.empty()) {
163 top_list[0]->adj = Scalar(1);
166 for (
auto& node : top_list | std::views::drop(1)) {
167 node->adj = Scalar(0);
174 for (
const auto& node : top_list) {
176 if (!node->is_leaf) {
177 node->accumulate_adjoints();
183 for (
const auto& [col, node] : output_list) {
185 triplets.emplace_back(row, col, node->adj);