I'm trying to calculate the laplacian of a 2d field with periodic boundary conditions (i.e. the divergence of the gradient) and I'm having trouble getting it to work.
I've tried two different methods. First I used an example from scipy.sparse:
def poisson2d(N,epsilon=1.0):
"""
Return a sparse CSR matrix for the 2d poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid.
"""
D = (2 + 2*epsilon)*ones(N*N)
T = -epsilon * ones(N*N)
O = -ones(N*N)
T[N-1::N] = 0
return spdiags([D,O,T,T,O],[0,-N,-1,1,N],N*N,N*N).tocoo().tocsr() #eliminate explicit zeros
dx=0.01
grid=arange(-1,1,dx)
N=len(grid)
D=poisson2d(N)
f=lambda x,y: x^2
phi=matrix([[f(x,y) for x in grid] for y in grid])
dphi2=D*phi.reshape((N**2,1))
And I calculated the laplacian using a filter:
dx=0.01
grid=arange(-1,1,dx)
N=len(grid)
f=lambda x,y: x**2
phi=array([[f(x,y) for x in grid] for y in grid])
stencil=[[0,1,0],[1,-4,1],[0,1,0]]
dphi2=filters.convolve(phi,stencil,mode='wrap')
In both cases I get the right answer in the middle of the field which for the function x**2 is just 2, but at the boundaries I get something totally wrong. Why isn't the 'wrap' mode working in the filter case?