v923z / micropython-ulab

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

Added test script for np.nonzero() #544

Closed tejalbarnwal closed 2 years ago

tejalbarnwal commented 2 years ago

added following script at ulab/tests/2d/numpy/nonzero.py

try:
   from ulab import numpy as np
except:
   import numpy as np

array = np.array(range(16)).reshape((4,4))
boolean_array = array < 3

# np.nonzero() returns a tuple of corresponding row and column 
# indices array for each element being true in boolean array
row_indices, column_indices = np.nonzero(boolean_array)

print("Given Array:\n", array)
print("\nBoolean Array:\n", boolean_array)
print("\nFollowing indices have non-zero values:")
for i in range(len(row_indices)):
    print("row", row_indices[i], "and column", column_indices[i])

The expected output file is located at ulab/tests/2d/numpy/nonzero.py.exp Expected output:

Given Array:
 array([[0.0, 1.0, 2.0, 3.0],
       [4.0, 5.0, 6.0, 7.0],
       [8.0, 9.0, 10.0, 11.0],
       [12.0, 13.0, 14.0, 15.0]], dtype=float64)

Boolean Array:
 array([[True, True, True, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)

Following indices have non-zero values:
row 0 and column 0
row 0 and column 1
row 0 and column 2
v923z commented 2 years ago

nonzero works with arrays of arbitrary dtype, so e.g., this is also valid:

>>> a = np.array(range(9), dtype=np.uint8).reshape((3,3)) - 4
>>> print(np.nonzero(a))

You can simply loop through the types like in https://github.com/v923z/micropython-ulab/blob/master/tests/2d/numpy/arange.py. Would you mind adding this, so that the test would be complete?

tejalbarnwal commented 2 years ago

sure, I will update with this

v923z commented 2 years ago

sure, I will update with this

OK, thanks! Let me know when are ready. The rest of the PR is done, so as soon as you can update your test script, we could merge this into master.

tejalbarnwal commented 2 years ago

I have updated the script to loop through different data types

v923z commented 2 years ago

Fantastic! Many thanks for sticking with it till the very end! I hope you enjoyed the ride, and I am looking forward to your future contributions.

tejalbarnwal commented 2 years ago

Yes, sure