Error with NumPy boolean type

Issue #42 closed
Pierre Denis
repo owner created an issue

The method lea.P fails when applied on a boolean expression involving NumPy array:

import numpy as np
dist = lea.vals(*np.array((1,2,3)))
dist > 2
# -> False : 0.6666666666666666
#    True  : 0.3333333333333333
lea.P(dist > 2)
# -> lea.lea.Error: found <bool_> value although <bool> is expected
(dist > 2).P
# -> lea.lea.Error: found <bool_> value although <bool> is expected

(reported by Neal Becker on Lea 3.0.0)

What happens is that lea.P calls a function checking that you provide a boolean expression. In the present case, the dist > 2 results is a distribution that contains NumPy's bool_ objects (note the underscore!). These display as True/False but… they are not instance of Python’s bool, nor even a subclass of bool. That’s why Lea reportS an error. You might reply that such check is anti-Pythonic... Yes, but my own experience using Lea convinced me that this consistency check is very handy to detect and report wrong expressions. I prefer to keep it.

Now, I agree that such error looks weird in the present case. This will be fixed for next Lea version (3.0.1)

In the meantime, I have two workarounds to propose:

1) You may deactivate the check, by creating the following function:

def Pr(d):
    return d._p(True,check_val_type=False)

then you should be able to do:

Pr(dist > 2)
# -> 0.3333333333333333

2) Alternatively, you may make the conversion to Python's bool explicitly:

(dist > 2).map(bool).P
# -> 0.3333333333333333

Comments (5)

  1. Log in to comment