Sometimes scipy.curve_fit raises a RuntimeError exception.
Example code (explicitly written to raise the exception):
import numpy
from scipy.optimize import curve_fit
def model(x, A, B):
return A * x B
data = numpy.array([[0, 1], [1, 2]])
par, cov = curve_fit(model, data[:, 0], data[:, 1], p0 = [0, 0], maxfev=1)
Running the code raises the exception
RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1.
I can catch the exception with
import numpy
from scipy.optimize import curve_fit
def model(x, A, B):
return A * x B
data = numpy.array([[0, 1], [1, 2]])
try:
par, cov = curve_fit(model, data[:, 0], data[:, 1], p0 = [0, 0], maxfev=1)
except RuntimeError:
print('Runtime Error!')
How can I retrieve the entire descriptive string of the exception, that is, the error message "Optimal parameters not found: Number of calls to function has reached maxfev = 1"?
CodePudding user response:
import numpy
from scipy.optimize import curve_fit
def model(x, A, B):
return A * x B
data = numpy.array([[0, 1], [1, 2]])
try:
par, cov = curve_fit(model, data[:, 0], data[:, 1], p0 = [0, 0], maxfev=1)
except RuntimeError as e:
print('Runtime Error :', str(e))
This catches the exception as a variable e and uses a string conversion to get the error info.
