I need to find vectorizing solution to filter 2D array by rows in another 2D array (with '0' mask)
Example with FOR loop:
import numpy as np
ma = np.array([ [0, 0, 2, 0, 0, 0, 3, 0],
[0, 0, 3, 0, 0, 0, 0, 2],
[0, 0, 2, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 3, 0, 0]])
ds = np.array([[2, 3, 3, 2, 1, 1, 1, 2],
[3, 3, 2, 2, 3, 2, 3, 3],
[3, 3, 2, 2, 3, 3, 3, 2],
[2, 1, 1, 3, 3, 3, 1, 2],
[1, 3, 2, 1, 1, 2, 1, 1],
[2, 3, 3, 2, 1, 1, 3, 2],
[3, 1, 2, 3, 3, 2, 3, 3],
[2, 1, 1, 2, 1, 2, 1, 1],
[2, 3, 3, 1, 3, 2, 3, 3],
[2, 1, 1, 3, 3, 3, 1, 2]])
result = np.zeros([ds.shape[0], ma.shape[0]], dtype = bool)
for i in range (ma.shape[0]):
ds_filtered = np.take(ds, ma[i,:].nonzero(), axis = 1).squeeze()
result [:,i] = np.equal(ds_filtered, ma[i,ma[i,:] != 0] ).all(axis = 1)
result:
array([[False, True, False, False],
[ True, False, False, False],
[ True, False, False, False],
[False, False, False, False],
[False, False, True, False],
[False, True, False, False],
[ True, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
It trying to find rows in DS where row in MA is equal exept ZEROS. Zeros in 'ma' array means ANY number in 'ds' array (some kind of mask) And such find for all rows in MA
Task 1 (minimum): rewrite this code without FOR, i.e. make vectorised solution
Task 2 (optimal): make vectorisation in Task 1 adopted to CuPy.
Task 3 (maximum): rewrite it in CUDA kernel to use it as a custom kernel in CuPy or Numba
Task 4 (Superior))) Optimise Task 2 or Task 3 to use bitwise data (np.packbits & np.view) instead of boolean array (8 bit per element). It allows make arrays 8x smaller (real size of data more than 400gb)
Thanks in advance!