Following this post I was advised to ask a different question based on MCVE. My objective is to implement the NumPy's convolve for arbitrary shaped input arrays. Please consider that I'm using the term convolution in the context of Cauchy product of multivariate power series (multivariable polynomial multiplication). SciPy functions such as signal.convolve
, ndimage.convolve
or ndimage.filters.convolve
do not work for me as I have explained here.
Consider two non-square 2D NumPy arrays A
and B
:
D1=np.array([4,5])
D2=np.array([2,3])
A=np.random.randint(10,size=D1)
B=np.random.randint(10,size=D2)
for example:
[[1 4 4 2 7]
[6 1 7 5 3]
[1 4 3 4 8]
[7 5 8 3 3]]
[[2 2 3]
[5 2 9]]
Now I'm able to calculate the elements of the C=convolve(A,B)
with conv(A,B,K)
:
def crop(A,D1,D2):
return A[tuple(slice(D1[i], D2[i]) for i in range(A.ndim))]
def sumall(A):
sum1=A
for k in range(A.ndim):
sum1 = np.sum(sum1,axis=0)
return sum1
def flipall(A):
return A[[slice(None, None, -1)] * A.ndim]
def conv(A,B,K):
D0=np.zeros(K.shape,dtype=K.dtype)
return sumall(np.multiply(crop(A,np.maximum(D0,np.minimum(A.shape,K-B.shape)) \
,np.minimum(A.shape,K)), \
flipall(crop(B,np.maximum(D0,np.minimum(B.shape,K-A.shape)) \
,np.minimum(B.shape,K)))))
Fow example for K=np.array([0,0])+1
, conve(A,B,K)
results 1*2=2
, for K=np.array([1,0])+1
results 5*1+2*6=17
, for K=np.array([0,1])+1
is 2*4+1*2=10
and for K=np.array([1,1])+1
gives 4*5+6*2+1*1+1*2=36
:
[[2 10 ...]
[17 36 ...]
... ]]
now if I knew the dimension of A
and B
I could nest some for loops to populate the C
, but that's not the case for me. How can I use the conv
function to populate the C
ndarray with a shape of C.shape=A.shape+B.shape-1
without using for loops?