Sleipnir C++ API
Loading...
Searching...
No Matches
expression_graph.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <ranges>
6
7#include <gch/small_vector.hpp>
8
9#include "sleipnir/autodiff/expression.hpp"
10
11namespace slp::detail {
12
20inline gch::small_vector<Expression*> topological_sort(
21 const ExpressionPtr& root) {
22 gch::small_vector<Expression*> list;
23
24 // If the root type is constant, updates are a no-op, so return an empty list
25 if (root == nullptr || root->type() == ExpressionType::CONSTANT) {
26 return list;
27 }
28
29 // Stack of nodes to explore
30 gch::small_vector<Expression*> stack;
31
32 // Enumerate incoming edges for each node via depth-first search
33 stack.emplace_back(root.get());
34 while (!stack.empty()) {
35 auto node = stack.back();
36 stack.pop_back();
37
38 for (auto& arg : node->args) {
39 // If the node hasn't been explored yet, add it to the stack
40 if (arg != nullptr && ++arg->incoming_edges == 1) {
41 stack.push_back(arg.get());
42 }
43 }
44 }
45
46 // Generate topological sort of graph from parent to child.
47 //
48 // A node is only added to the stack after all its incoming edges have been
49 // traversed. Expression::incoming_edges is a decrementing counter for
50 // tracking this.
51 //
52 // https://en.wikipedia.org/wiki/Topological_sorting
53 stack.emplace_back(root.get());
54 while (!stack.empty()) {
55 auto node = stack.back();
56 stack.pop_back();
57
58 list.emplace_back(node);
59
60 for (auto& arg : node->args) {
61 // If we traversed all this node's incoming edges, add it to the stack
62 if (arg != nullptr && --arg->incoming_edges == 0) {
63 stack.push_back(arg.get());
64 }
65 }
66 }
67
68 return list;
69}
70
77inline void update_values(const gch::small_vector<Expression*>& list) {
78 // Traverse graph from child to parent and update values
79 for (auto& node : list | std::views::reverse) {
80 auto& lhs = node->args[0];
81 auto& rhs = node->args[1];
82
83 if (lhs != nullptr) {
84 if (rhs != nullptr) {
85 node->val = node->value(lhs->val, rhs->val);
86 } else {
87 node->val = node->value(lhs->val, 0.0);
88 }
89 }
90 }
91}
92
93} // namespace slp::detail