SciPy curve_fit runtime error, stopping iteration

makhlaghi picture makhlaghi · Feb 7, 2012 · Viewed 13.7k times · Source

I am using scipy.optimize.curve_fit() in an iterative way.

My problem is that when ever it is unable to fit the parameters the whole program (and thus the iteration) stops, this is the error it gives:

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

I understand that why it has been unable to fit. My problem is that is there any way I can write the program in Python 3.2.2 that will ignore such occurrences and just continue?

Answer

talonmies picture talonmies · Feb 7, 2012

You can use standard Python exception handling to trap the error raised by curve_fit in cases where the optimization fails to find a solution. So something like:

try:
    popt,pcov = scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None)

except RuntimeError:
    print("Error - curve_fit failed")

That construct will let you catch and handle the error condition raised by curve_fit without having your program abort.