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