Abhisek92

Vectorized Convolve

Jun 10th, 2019
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def get_window(index, arr, widths):
  4.     if len(index) == len(arr.shape) == len(widths):
  5.         index = np.array(index)
  6.         max_indices = np.array(arr.shape)
  7.         widths = np.array(widths)
  8.         win_start = index - widths
  9.         win_end = index + (widths + 1)    
  10.         win_start[win_start < 0] = 0
  11.         max_mask = win_end > max_indices
  12.         win_end = (max_mask * max_indices) + (~max_mask * win_end)
  13.         indexer = tuple(map(slice, win_start, win_end))
  14.         return  arr[indexer]
  15.     else:
  16.         raise ValueError("Shape mismatch!")
  17.  
  18. def generate_indices(arr_shape):
  19.     idx = np.indices(arr_shape)
  20.     dt = ('int, ' * idx.shape[0])[:-2]
  21.     i = 0
  22.     out = np.zeros(arr_shape, dtype=dt)
  23.     for indx in list(out.dtype.fields.keys()):
  24.         out[indx] = idx[i]
  25.         i += 1
  26.     return out.astype(object)
  27.  
  28.  
  29. vget_window = np.vectorize(get_window, excluded=['arr', 'widths'], otypes=[object])
  30.  
  31.  
  32. def convolve_function(arr, widths, vfunc):
  33.     indxs = generate_indices(arr.shape)
  34.     slices = vget_window(index=indxs, arr=arr, widths=widths)
  35.     return vfunc(slices)
Add Comment
Please, Sign In to add comment