I was the one who recommended vectorizing. I think the first approach would be to convert your code to using 2D indexes. I think this will make the vectorizing clearer:
for j in range(rows):
for i in range(cols):
i1 = i+1 if i<cols-1 else i-1
i2 = i-1 if i>0 else i+1
j1 = j+1 if j<rows-1 else j-1
j2 = j-1 if j>0 else j+1
w1 = U[j, i]
w2 = U[j, i-1] if i > 0 else U[j, i]
w3 = V[j, i]
w4 = V[j-1, i] if j > 0 else V[j, i]
p = parray[j, i]
p1 = parray[j, i1]
p2 = parray[j, i2]
p3 = parray[j1, i]
p4 = parray[j2, i]
zarray[j, i] = (w1 + w2 + w3 + w4)*p - (w1*p1 + w2*p2 + w3*p3 + w4*p4)
So, if I am reading this code right, you are shifting some rows and columns around. So the next step is to re-implement this by making copies of the arrays that follow the same patterns:
U1 = np.empty_like(U)
V1 = np.empty_like(V)
parray1 = np.empty_like(parray)
parray2 = np.empty_like(parray)
parray3 = np.empty_like(parray)
parray4 = np.empty_like(parray)
U1[:, 1:] = U[:, :-1] # this is w2
V1[1:, :] = V[:-1, :] # this is w4
U1[:, 0] = U[:, 0]
V1[0, :] = V[0, :]
parray1[:, :-1] = parray[:, 1:] # this is the result of k1
parray2[:, 1:] = parray[:, :-1] # this is the result of k2
parray3[:-1, :] = parray[1:, :] # this is the result of k3
parray4[1:, :] = parray[:-1, :] # this is the result of k4
parray1[:, -1] = parray[:, -2]
parray2[:, 0] = parray[:, 1]
parray3[-1, :] = parray[-2, :]
parray4[0, :] = parray[1, :]
zarray = (U+U1+V+V1)*parray - (U*parray1 + U1*parray2 + V*parray3 + V1*parray4)
You could also use np.hstack
and np.vstack
instead of slices:
U1 = np.hstack([U[:, :1], U[:, :-1]])
V1 = np.vstack([V[:1, :], V[:-1, :]])
parray1 = np.hstack([parray[:, 1:], parray[:, -2:-1]])
parray2 = np.hstack([parray[:, 1:2], parray[:, :-1]])
parray3 = np.vstack([parray[1:, :], parray[-2:-1, :]])
parray4 = np.vstack([parray[1:2, :], parray[:-1, :]])
zarray = (U+U1+V+V1)*parray - (U*parray1 + U1*parray2 + V*parray3 + V1*parray4)