Parsing a string input into a lambda function with multiple parameters

93 Views Asked by At

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.

1

There are 1 best solutions below

1
leaf_yakitori On
  • you can just use eval to achieve it with some extra input.
  • input:
input a lambda: x,a,b,c,d:a*np.exp(-x)*b/c+d
  • example code:
import numpy as np
from scipy.optimize import curve_fit
x = np.arange(100)
y = 2*np.exp(-x)*3.14/2+1
fx = input("input a lambda: ")
f = eval("lambda "+fx)
p,pcov=curve_fit(f,x,y)
  • If you really want to write the parse(), basically rewrite the python interpreter, which is overkill to this problem.