I want to create a large (say 10^5 x 10^5) sparse circulant matrix in Python. It has 4 elements per row at positions [i,i+1], [i,i+2], [i,i+N-2], [i,i+N-1]
, where I have assumed periodic boundary conditions for the indices (i.e. [10^5,10^5]=[0,0], [10^5+1,10^5+1]=[1,1]
and so on). I looked at the scipy sparse matrices documentation but I am quite confused (I am new to Python).
I can create the matrix with numpy
import numpy as np
def Bc(i, boundary):
"""(int, int) -> int
Checks boundary conditions on index
"""
if i > boundary - 1:
return i - boundary
elif i < 0:
return boundary + i
else:
return i
N = 100
diffMat = np.zeros([N, N])
for i in np.arange(0, N, 1):
diffMat[i, [Bc(i+1, N), Bc(i+2, N), Bc(i+2+(N-5)+1, N), Bc(i+2+(N-5)+2, N)]] = [2.0/3, -1.0/12, 1.0/12, -2.0/3]
However, this is quite slow and for large N
uses a lot of memory, so I want to avoid the creation with numpy and the converting to a sparse matrix and go directly to the latter.
I know how to do it in Mathematica, where one can use SparseArray and index patterns - is there something similar here?