v923z / micropython-ulab

a numpy-like fast vector module for micropython, circuitpython, and their derivatives
https://micropython-ulab.readthedocs.io/en/latest
MIT License
403 stars 111 forks source link

Implement logical operators __or__, __and__ and __xor__ for ndarrays #588

Closed mtroback closed 1 year ago

mtroback commented 1 year ago

Describe the solution you'd like I'm missing the elementwise operators |, & and ^ for boolean ndarrays.

Additional context This is some amazing work you have done with ulab, I'm really greatful, thanks!

I hope this isn't already in place and I missed something. I'm running ulab on RPi pico using pimoroni-pico-v1.19.12-micropython.uf2

When I test it I get: TypeError: unsupported types for __or__: 'ndarray', 'ndarray'

v923z commented 1 year ago

Those operators are indeed not implemented, but could be added. Here is a list: https://github.com/v923z/micropython-ulab/blob/f2dd2230c4fdf1aa5c7a160782efdde18e8204bb/code/ulab.h#L96-L187

Do you also want the in-place operators?

v923z commented 1 year ago

@mtroback Martin, could you, please, check out this branch and see if you can work with it? https://github.com/v923z/micropython-ulab/tree/logical

mtroback commented 1 year ago

I'll see what I can do today, thanks!

mtroback commented 1 year ago

@v923z I've tested it, and while the function works as expected, the returned ndarray has changed type to uint16. I read about the upcasting (https://micropython-ulab.readthedocs.io/en/latest/ulab-ndarray.html#upcasting) but I'm not sure I would expect that to happen here while operating on 2 dtype=np.bool ndarrays?

>>> a = np.array([True, False], dtype=np.bool)
>>> b = ~a
>>> a | b
array([1, 1], dtype=uint16)
>>> a & b
array([0, 0], dtype=uint16)
v923z commented 1 year ago

@v923z I've tested it, and while the function works as expected, the returned ndarray has changed type to uint16. I read about the upcasting (https://micropython-ulab.readthedocs.io/en/latest/ulab-ndarray.html#upcasting) but I'm not sure I would expect that to happen here while operating on 2 dtype=np.bool ndarrays?

No, that's definitely wrong, thanks for bringing it up!

v923z commented 1 year ago

@mtroback OK, so this brought up two other errors, namely, the same issue for the +, and * operators. These are fixed now in the latest commit.

mtroback commented 1 year ago

Looking good! Thank you!

On a side note, is this not supposed to work?

>>> b
array([False, True, False], dtype=bool)
>>> b[-1] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object isn't iterable
v923z commented 1 year ago

On a side note, is this not supposed to work?

It should work, it's definitely not correct. Thanks!

v923z commented 1 year ago

Closed through https://github.com/v923z/micropython-ulab/pull/639