New User: Errors using Indexed expressions with diff and Sum while using codegen

34 views
Skip to first unread message

ajp

unread,
Dec 6, 2022, 7:28:30 AM12/6/22
to sympy

Hi,

Very new to Sympy. Hoping to generate a Sum of an indexed expression, then form a simple expression, and then take derivatives. Finally, I'd like to output the solution using codegen. I'm really struggling. I suspect my use of Sum and or indexed expressions is wrong. All help really appreciated:

import sympy as sm

# would prefer to use the first one of these
#Ns = sm.symbols('Ns', cls=sm.Idx) # gives IndexError: tuple index out of range
Ns = 10 # gives FIXME: No specialized handling of type <class 'sympy.concrete.summations.Sum'>

sp = sm.Idx('sp', Ns)
S = sm.IndexedBase('S')[sp]
total = sm.Sum(S, sp)

# construct simple expression
func = sm.log(S/total)
print(func)

# derivative of Sum
d_total = total.diff(S)
print(d_total)

# derivative of expression
d_func = func.diff(S)
print(d_func)

# print
from sympy.utilities.codegen import codegen
codegen( [("func", func), ("dfunc", d_func)], language="C", prefix="test", to_files=True, header=False, empty=False)

Aaron Meurer

unread,
Dec 6, 2022, 5:10:57 PM12/6/22
to sy...@googlegroups.com
The problem is that codegen doesn't support generating Sum yet. It's
something we want to add, but it's harder because a summation requires
generating code for a loop.

Since you know the bounds of the summation ahead of time, you can
evaluate it to a normal addition using doit() (the expression for the
derivative can also be simplified. I would suggest
d_func.expand().doit()).

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/3c9728f8-e406-410f-afb0-b72974f7c6e2n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages