Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch OptimizeWarning as an exception

I was just trying to catch an OptimizeWarning thrown by the scipy.optimize.curve_fit function, but I realized it was not recognized as a valid exception.

This is a non-working simple idea of what I'm doing:

from scipy.optimize import curve_fit
try:
    popt, pcov = curve_fit(some parameters)
except OptimizeWarning:
    print 'Maxed out calls.'
    # do something

I looked around the docs but there was nothing there.

Am I missing something obvious or is it simply not defined for some reason?

BTW, this is the full warning I get and that I want to catch:

/usr/local/lib/python2.7/dist-packages/scipy/optimize/minpack.py:604: OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)
like image 882
Gabriel Avatar asked Dec 25 '22 17:12

Gabriel


1 Answers

You can require that Python raise this warning as an exception using the following code:

import warnings
from scipy.optimize import OptimizeWarning

warnings.simplefilter("error", OptimizeWarning)
# Your code here

Issues with warnings

Unfortunately, warnings in Python have a few issues you need to be aware of.

Multiple filters

First, there can be multiple filters, so your warning filter can be overridden by something else. This is not too bad and can be worked around with the catch_warnings context manager:

import warnings
from scipy.optimize import OptimizeWarning

with warnings.catch_warnings():
    warnings.simplefilter("error", OptimizeWarning)
    try:
        # Do your thing 
    except OptimizeWarning:
        # Do your other thing 

Raised Once

Second, warnings are only raised once by default. If your warning has already been raised before you set the filter, you can change the filter, it won't raise the warning again.

To my knowledge, there unfortunately is not much you can do about this. You'll want to make sure you run the warnings.simplefilter("error", OptimizeWarning) as early as possible.

like image 157
Thomas Orozco Avatar answered Dec 28 '22 23:12

Thomas Orozco