Reputation: 47
Can I substitute a IndexedBase with a numpy array to get a new sympy expression? Something like:
import numpy as np
import sympy as sy
A = sy.IndexedBase('A', shape=(5))
k = sy.IndexedBase('k', shape=(5))
i = sy.symbols('i',cls=sy.Idx)
expr1 = sy.Sum(A[i]/sy.exp(sy.I * k[i]),(i,1,5))
kz = np.arange(1,5)
expr2 = expr1.subs(k[:],kz[:])
last line = error.
Thanks!
Upvotes: 0
Views: 200
Reputation: 1
This might work for you!
import numpy as np
import sympy as sp
import inspect
i ,m= sp.symbols('i,m', integer=True)
A = sp.IndexedBase('A', shape=(m))
k = sp.IndexedBase('k', shape=(m))
#i = sp.symbols('i',cls=sy.Idx)
expr1 = sp.Sum(A[i]/sp.exp(sp.I * k[i]),(i,0,m-1))
print(expr1)
print(expr1.doit())
f_lam = sp.lambdify((A, k,m), expr1, 'numpy')
print(inspect.getsource(f_lam))
M=5
A2 = np.random.uniform(0,1, M)
kz = np.arange(0,M)
print(f_lam(A2,kz,M))
#(-0.08145603175240379+0.27923362018114933j)
Upvotes: 0
Reputation: 1957
Yes, you can:
In [6]: expr2 = expr1.replace(k, kz)
In [7]: expr2
Out[7]:
5
___
╲
╲ -ⅈ⋅[1, 2, 3, 4, 5][i]
╱ ℯ ⋅A[i]
╱
‾‾‾
i = 1
Beware that the summation range is wrong, Python arrays have zero as offset.
Upvotes: 1