How can I parse a string input into the proper form which could be used as the first callable parameter of scipy.optimize.curve_fit?
import numpy as np
from scipy.optimize import curve_fit
x = np.arange(100)
y = 2*np.exp(-x)*3.14/2+1
The string is a math formula inputted by some users with no knowledge of Python. The parse function take these formulas as input:
f = parse('a*exp(-x)*b/c+d')
f1 = parse('k*x+b')
f2 = parse('k*sin(x*w)+b')
and parse / interpret them to python lambda functions:
f = lambda x,a,b,c,d: a*numpy.exp(-x)*b/c+d
f1 = lambda x,k,b: k*x+b
f2 = lambda x,k,w,b: k*sin(x*w)+b
so that f can be called by curve_fit
p,pcov = curve_fit(f,x,y)
I've found a similar question on Stack Overflow but there are no answers or comments.
evalto achieve it with some extra input.parse(), basically rewrite the python interpreter, which is overkill to this problem.