about the difference between what symp prints on screen and what passes in the code

17 views
Skip to first unread message

Zohreh Karimzadeh

unread,
Sep 13, 2022, 1:15:34 AM9/13/22
to sympy
Dear Sympy
Please let me know what is the format of sympy expression after printing on screen?
As can be seen based on the following code:
   --------------------------------------------------------------------------

from contextlib import redirect_stdout
from io import StringIO
from lmfit.models import ExpressionModel
import matplotlib.pyplot as plt
from numpy import exp, linspace, sin
import sympy
off, am, x , x0, phase = sympy.symbols('off, am, x , x0, phase')
f = StringIO()
with redirect_stdout(f):
     expr = off + am * sympy.exp(-x / x0) * sympy.sin(x * phase)
     print(expr)
s = f.getvalue()
mod = ExpressionModel(expr, independent_vars=['x'])

x = linspace(0, 10, 501)
a = dict(off=0.25, am=1.0, x0=2.0, phase=0.04)
b = dict(x=x)
params = mod.make_params(**a)
y = mod.eval(params, **b)
out = mod.fit(y, params, **b)
print(out.fit_report())
plt.plot(x, y, 'o')
plt.plot(x, out.init_fit, '--', label='initial fit')
plt.plot(x, out.best_fit, '-', label='best fit')
--------------------------------------------------------------------
It gives error:

   [ self.expr = expr.strip()
AttributeError: 'Add' object has no attribute 'strip']

Which means expr is not recognized by ExpressionModel, while if instead of expr, s is passed in  ExpressionModel as follow :
mod = ExpressionModel(s, independent_vars=['x'])
Then it works pretty well.
Is there another way to make a string from a sympy expression that in it sympy.exp or sympy.log  changed to exp and log. Parse and replace doesn't work because in real example is not fully executed.
Regards,
zk

Kuldeep Borkar

unread,
Sep 13, 2022, 4:46:29 AM9/13/22
to sy...@googlegroups.com
Hi,
I think you can simply use typecasting for converting the sympy expr to a normal string like;
mod = ExpressionModel(str(expr), independent_vars=['x'])
and it should work : )

--
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/4feb9a7e-3ba8-4574-a9c7-884464fb6a8fn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages