17#include <gch/small_vector.hpp>
19#include "sleipnir/autodiff/expression_type.hpp"
20#include "sleipnir/util/force_inline.hpp"
21#include "sleipnir/util/function_ref.hpp"
22#include "sleipnir/util/intrusive_shared_ptr.hpp"
23#include "sleipnir/util/pool.hpp"
25namespace slp::detail {
28inline constexpr bool USE_POOL_ALLOCATOR =
false;
30inline constexpr bool USE_POOL_ALLOCATOR =
true;
33template <
typename Scalar>
39template <
typename Scalar>
40using ExpressionPtr = IntrusiveSharedPtr<Expression<Scalar>>;
47template <
typename Derived,
typename... Args>
48static ExpressionPtr<typename Derived::Scalar> make_expression_ptr(
50 if constexpr (USE_POOL_ALLOCATOR) {
51 return allocate_intrusive_shared<Derived>(global_pool_allocator<Derived>(),
52 std::forward<Args>(args)...);
54 return make_intrusive_shared<Derived>(std::forward<Args>(args)...);
58template <
typename Scalar, ExpressionType Type>
59struct BinaryMinusExpression;
61template <
typename Scalar, ExpressionType Type>
62struct BinaryPlusExpression;
64template <
typename Scalar, ExpressionType Type>
67template <
typename Scalar, ExpressionType Type>
70template <
typename Scalar, ExpressionType Type>
71struct UnaryMinusExpression;
81template <
template <
typename, ExpressionType>
typename Derived,
typename Scalar,
83SLEIPNIR_FORCE_INLINE ExpressionPtr<Scalar> make_typed_expression_ptr(
84 ExpressionType type,
const Args&... args) {
85 using enum ExpressionType;
87 if (type == PARAMETER) {
88 return make_expression_ptr<Derived<Scalar, PARAMETER>>(args...);
89 }
else if (type == LINEAR) {
90 return make_expression_ptr<Derived<Scalar, LINEAR>>(args...);
91 }
else if (type == QUADRATIC) {
92 return make_expression_ptr<Derived<Scalar, QUADRATIC>>(args...);
94 return make_expression_ptr<Derived<Scalar, NONLINEAR>>(args...);
102template <
typename Scalar>
103ExpressionPtr<Scalar> constant_ptr(Scalar value);
114template <
typename Value,
typename Scalar>
115Value lit(Scalar value) {
116 if constexpr (std::same_as<Value, Scalar>) {
119 return constant_ptr(value);
126template <
typename Scalar_>
177 return type() == ExpressionType::CONSTANT &&
val == constant;
186 using enum ExpressionType;
192 }
else if (
rhs->is_constant(
Scalar(0))) {
195 }
else if (
lhs->is_constant(
Scalar(1))) {
198 }
else if (
rhs->is_constant(
Scalar(1))) {
204 if (
lhs->type() == CONSTANT &&
rhs->type() == CONSTANT) {
205 return constant_ptr(
lhs->val *
rhs->val);
210 auto type = NONLINEAR;
211 if (
lhs->type() <= PARAMETER ||
rhs->type() <= PARAMETER) {
213 }
else if (
lhs->type() == LINEAR &&
rhs->type() == LINEAR) {
225 using enum ExpressionType;
231 }
else if (
rhs->is_constant(
Scalar(1))) {
237 if (
lhs->type() == CONSTANT &&
rhs->type() == CONSTANT) {
238 return constant_ptr(
lhs->val /
rhs->val);
243 auto type =
rhs->type() <= PARAMETER ? std::max(
lhs->type(),
rhs->type())
254 using enum ExpressionType;
261 }
else if (
rhs ==
nullptr ||
rhs->is_constant(
Scalar(0))) {
267 if (
lhs->type() == CONSTANT &&
rhs->type() == CONSTANT) {
268 return constant_ptr(
lhs->val +
rhs->val);
271 auto type = std::max(
lhs->type(),
rhs->type());
291 using enum ExpressionType;
302 }
else if (
rhs->is_constant(
Scalar(0))) {
308 if (
lhs->type() == CONSTANT &&
rhs->type() == CONSTANT) {
309 return constant_ptr(
lhs->val -
rhs->val);
312 auto type = std::max(
lhs->type(),
rhs->type());
321 using enum ExpressionType;
330 if (
lhs->type() == CONSTANT) {
331 return constant_ptr(-
lhs->val);
363 virtual ExpressionType
type()
const = 0;
368 virtual std::string_view
name()
const = 0;
405template <
template <
typename, ExpressionType>
typename Derived,
typename Scalar,
417 template <
typename...
Args>
418 requires(
sizeof...(Args) ==
NumArgs &&
422 :
args{std::forward<Args>(
args)...} {}
429 [&]<
size_t...
Is>(std::index_sequence<
Is...>) {
431 }(std::make_index_sequence<NumArgs>{});
438 return [&]<
size_t...
Is>(std::index_sequence<
Is...>) {
439 return static_cast<const Self&
>(*this).eval(
args[
Is]->
val...);
440 }(std::make_index_sequence<NumArgs>{});
462 [&]<
size_t...
Is>(std::index_sequence<
Is...>) {
464 std::array<Scalar, NumArgs> g{};
465 grad(g, this->
val, args[
Is]->
val...);
469 }(std::make_index_sequence<NumArgs>{});
474 [&]<
size_t...
Is>(std::index_sequence<
Is...>) {
477 if constexpr (Self::CONSTANT_PARTIALS) {
479 std::array<Scalar, NumArgs> g{};
480 grad(g, this->
val, args[
Is]->
val...);
492 args[
Is]->adj_expr += this->adj_expr * constant_ptr(g[
Is]);
498 std::array<ExpressionPtr<Scalar>,
NumArgs> g;
506 if (g[
Is] !=
nullptr) {
507 args[
Is]->adj_expr += this->adj_expr * g[
Is];
512 }(std::make_index_sequence<NumArgs>{});
530 template <
typename Value,
typename...
Args>
531 void grad(std::array<Value, NumArgs>& g,
const Value&
val,
532 const Args&... x)
const {
533 if constexpr (
requires(
const Self& expr) {
534 expr.eval_grad(g,
val, x...);
536 static_cast<const Self&
>(*this).eval_grad(g,
val, x...);
551template <
template <
typename, ExpressionType>
typename Derived,
typename Scalar,
553ExpressionPtr<Scalar> fold_or_make(
const Args&... args) {
554 using enum ExpressionType;
556 if (((args->type() == CONSTANT) && ...)) {
557 Scalar val = Derived<Scalar, NONLINEAR>::eval(args->val...);
558 if constexpr (
sizeof...(Args) == 1) {
559 const auto& x = std::get<0>(std::forward_as_tuple(args...));
564 return constant_ptr(val);
567 if (((args->type() <= PARAMETER) && ...)) {
568 return make_expression_ptr<Derived<Scalar, PARAMETER>>(args...);
570 return make_expression_ptr<Derived<Scalar, NONLINEAR>>(args...);
578template <
typename Scalar, ExpressionType Type>
581 using BinaryMinusExpression::NonLeafExpression::NonLeafExpression;
584 static constexpr std::string_view
NAME =
"binary minus";
591 template <
typename Value>
592 static void eval_grad(std::array<Value, 2>& g,
605template <
typename Scalar, ExpressionType Type>
608 using BinaryPlusExpression::NonLeafExpression::NonLeafExpression;
611 static constexpr std::string_view
NAME =
"binary plus";
618 template <
typename Value>
619 static void eval_grad(std::array<Value, 2>& g,
632template <
typename Scalar, ExpressionType Type>
634 using DivExpression::NonLeafExpression::NonLeafExpression;
637 static constexpr std::string_view
NAME =
"division";
641 template <
typename Value>
642 static void eval_grad(std::array<Value, 2>& g,
654template <
typename Scalar, ExpressionType Type>
657 using MultExpression::NonLeafExpression::NonLeafExpression;
660 static constexpr std::string_view
NAME =
"multiplication";
664 template <
typename Value>
665 static void eval_grad(std::array<Value, 2>& g,
677template <
typename Scalar, ExpressionType Type>
680 using UnaryMinusExpression::NonLeafExpression::NonLeafExpression;
683 static constexpr std::string_view
NAME =
"unary minus";
690 template <
typename Value>
691 static void eval_grad(std::array<Value, 1>& g,
702template <
typename Scalar>
703constexpr void inc_ref_count(Expression<Scalar>* expr) {
712template <
typename Scalar>
713void deallocate_expression(Expression<Scalar>* expr) {
718 gch::small_vector<Expression<Scalar>*> stack;
719 stack.emplace_back(expr);
723 auto release = [&stack](Expression<Scalar>* child) {
724 if (--child->ref_count == 0) {
725 stack.emplace_back(child);
729 while (!stack.empty()) {
730 auto elem = stack.back();
733 if (elem->adj_expr !=
nullptr) {
734 release(elem->adj_expr.get());
736 elem->visit_args(release);
740 if constexpr (USE_POOL_ALLOCATOR) {
741 auto alloc = global_pool_allocator<Expression<Scalar>>();
742 std::allocator_traits<
decltype(alloc)>::deallocate(alloc, elem, 1);
744 operator delete(elem);
753template <
typename Scalar>
754constexpr void dec_ref_count(Expression<Scalar>* expr) {
755 if (--expr->ref_count == 0) {
756 deallocate_expression(expr);
763template <
typename Scalar>
773 ExpressionType
type()
const override {
return ExpressionType::CONSTANT; }
775 std::string_view
name()
const override {
return "constant"; }
778template <
typename Scalar>
786template <
typename Scalar>
799 ExpressionType
type()
const override {
return ExpressionType::LINEAR; }
801 std::string_view
name()
const override {
return "decision variable"; }
810template <
typename Scalar>
823 ExpressionType
type()
const override {
return ExpressionType::PARAMETER; }
825 std::string_view
name()
const override {
return "parameter"; }
Definition intrusive_shared_ptr.hpp:27
Definition function_ref.hpp:13
Definition expression.hpp:580
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:587
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:584
Definition expression.hpp:607
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:611
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:614
Definition expression.hpp:764
ExpressionType type() const override
Definition expression.hpp:773
Scalar value() const override
Definition expression.hpp:771
std::string_view name() const override
Definition expression.hpp:775
constexpr ConstantExpression(Scalar value)
Definition expression.hpp:768
Definition expression.hpp:787
Scalar value() const override
Definition expression.hpp:797
std::string_view name() const override
Definition expression.hpp:801
constexpr DecisionVariableExpression(Scalar value)
Definition expression.hpp:794
ExpressionType type() const override
Definition expression.hpp:799
constexpr DecisionVariableExpression()
Constructs a decision variable expression with a value of zero.
Definition expression.hpp:789
Definition expression.hpp:633
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:637
Definition expression.hpp:127
Scalar val
The value of the expression node.
Definition expression.hpp:132
virtual Scalar value() const =0
ExpressionPtr< Scalar > adj_expr
Definition expression.hpp:139
friend ExpressionPtr< Scalar > operator-(const ExpressionPtr< Scalar > &lhs)
Definition expression.hpp:320
virtual void accumulate_adjoints() const
Accumulates the child adjoints as Scalars.
Definition expression.hpp:378
uint32_t is_leaf
Definition expression.hpp:160
uint32_t ref_count
Reference count for intrusive shared pointer.
Definition expression.hpp:153
friend ExpressionPtr< Scalar > operator+(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:252
int32_t scratch
Definition expression.hpp:150
Scalar adj
The adjoint of the expression node, used during autodiff.
Definition expression.hpp:135
constexpr Expression()=default
Constructs a constant expression with a value of zero.
Scalar_ Scalar
Scalar type alias.
Definition expression.hpp:129
virtual ExpressionType type() const =0
friend ExpressionPtr< Scalar > operator/(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:223
friend ExpressionPtr< Scalar > operator-(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:289
friend ExpressionPtr< Scalar > operator*(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:184
virtual std::string_view name() const =0
virtual void accumulate_adjoints_expr() const
Accumulates the child adjoints as Expressions.
Definition expression.hpp:381
virtual void visit_args(function_ref< void(Expression< Scalar > *arg)> func) const
Definition expression.hpp:348
SLEIPNIR_FORCE_INLINE constexpr bool is_constant(Scalar constant) const
Definition expression.hpp:176
virtual bool has_constant_partials() const
Definition expression.hpp:375
friend ExpressionPtr< Scalar > operator+=(ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:280
constexpr Expression(Scalar value)
Definition expression.hpp:168
friend ExpressionPtr< Scalar > operator+(const ExpressionPtr< Scalar > &lhs)
Definition expression.hpp:341
Definition expression.hpp:656
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:660
Definition expression.hpp:407
constexpr NonLeafExpression(Args &&... args)
Definition expression.hpp:421
bool has_constant_partials() const final
Definition expression.hpp:458
void accumulate_adjoints() const final
Accumulates the child adjoints as Scalars.
Definition expression.hpp:461
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:409
ExpressionType type() const final
Definition expression.hpp:446
std::array< ExpressionPtr< Scalar >, NumArgs > args
The arguments in visit_args() order.
Definition expression.hpp:412
void accumulate_adjoints_expr() const final
Accumulates the child adjoints as Expressions.
Definition expression.hpp:473
std::string_view name() const final
Definition expression.hpp:451
void visit_args(function_ref< void(Expression< Scalar > *arg)> func) const final
Definition expression.hpp:427
Scalar value() const final
Definition expression.hpp:437
Definition expression.hpp:811
constexpr ParameterExpression(Scalar value)
Definition expression.hpp:818
ExpressionType type() const override
Definition expression.hpp:823
Scalar value() const override
Definition expression.hpp:821
constexpr ParameterExpression()
Constructs a parameter expression with a value of zero.
Definition expression.hpp:813
std::string_view name() const override
Definition expression.hpp:825
Definition expression.hpp:679
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:683
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:686