Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserWarning: converting a masked element to nan

Tags:

python

numpy

Executing a python script (way to long to include here) I wrote leads to a warning message. I don't know at which line in my code this gets raised. How can I get this information?

Furthermore, what does this mean exactly? In fact, I didn't know I was using a masked array of some sort?

/usr/lib/pymodules/python2.7/numpy/ma/core.py:3785: UserWarning: Warning: converting a masked element to nan.
warnings.warn("Warning: converting a masked element to nan.")
like image 453
HyperCube Avatar asked Apr 26 '13 12:04

HyperCube


2 Answers

You can use the warnings module to convert warnings to exceptions. The simplest method is called simplefilter. Here's an example; the code that generates the warning is in func2b(), so there is a nontrival traceback.

import warnings


def func1():
    print("func1")

def func2():
    func2b()
    print("func2")

def func2b():
    warnings.warn("uh oh")

def func3():
    print("func3")


if __name__ == "__main__":
    # Comment the following line to see the default behavior.
    warnings.simplefilter('error', UserWarning)
    func1()
    func2()
    func3()

When the line containing the call to simplefilter is commented out, the output is

func1
warning_to_exception.py:13: UserWarning: uh oh
  warnings.warn("uh oh")
func2
func3

With that line included, you get a traceback:

func1
Traceback (most recent call last):
  File "warning_to_exception.py", line 23, in <module>
    func2()
  File "warning_to_exception.py", line 9, in func2
    func2b()
  File "warning_to_exception.py", line 13, in func2b
    warnings.warn("uh oh")
UserWarning: uh oh
like image 109
Warren Weckesser Avatar answered Oct 29 '22 11:10

Warren Weckesser


It's also possible to patch MaskedArray.__float__ so that it raises an exception, this way you would see stack trace, which would include your code. And patching could be done in your code, no need to mess with the .../ma/core.py.

Example for squeeze():

import numpy as np
from numpy import ma

def raise_me(*args, **kw):
    raise Exception('ping')

ma.MaskedArray.squeeze = raise_me

def test():
    x = np.array([(1, 1.), (2, 2.)], dtype=[('a',int), ('b', float)])
    m = x.view(ma.MaskedArray)
    m.squeeze()

def main():
    test()

main()

And output:

Traceback (most recent call last):
  File "t.py", line 19, in <module>
    main()
  File "t.py", line 17, in main
    test()
  File "t.py", line 13, in test
    m.squeeze()
  File "t.py", line 6, in raise_me
    raise Exception('ping')
Exception: ping

As you can see it shows you the line with m.squeeze().

like image 25
gatto Avatar answered Oct 29 '22 10:10

gatto