我正在用一个简单的编码结构来模拟尺寸大于3的铁磁体的Ising Model,但是在效率上有一些问题。在我的代码中,有一个特定的函数是瓶颈。在
在仿真过程中,有必要找到一个给定站点的最近邻点。例如,在2D-Ising模型中,自旋占据晶格的每一点,用两个数字表示:(x,y)。(x,y)点的最近邻是四个相邻值,即(x+1,y),(x-1,y),(x,y+1),(x,y-1)。在5D中,某个晶格位置的自旋有10个最近邻的坐标(a、b、c、d、e),其形式与之前相同,但只针对元组中的每个点。在
下面是给出以下输入的代码:
"site_i is a random value between 0 and n-1 denoting the site of the ith spin"
"coord is an array of size (n**dim,dim) that contains the coordinates of ever spin"
"spins is an array of shape (n**dim,1) that contains the spin values (-1 or 1)"
"n is the lattice size and dim is the dimensionality"
"neighbor_coupling is the number that tells the function to return the neighbor spins that are one spacing away, two spacing away, etc."
def calc_neighbors(site_i,coord,spins,n,dim,neighbor_coupling):
# Extract all nearest neighbors
# Obtain the coordinates of each nearest neighbor
# How many neighbors to extract
num_NN = 2*dim
# Store the results in a result array
result_coord = np.zeros((num_NN,dim))
result_spins = np.zeros((num_NN,1))
# Get the coordinates of the ith site
site_coord = coord[site_i]
# Run through the + and - for each scalar value in the vector in site_coord
count = 0
for i in range(0,dim):
assert count <= num_NN, "Accessing more than nearest neighbors values."
site_coord_i = site_coord[i]
plus = site_coord_i + neighbor_coupling
minus = site_coord_i - neighbor_coupling
# Implement periodic boundaries
if (plus > (n-1)): plus = plus - n
if (minus < 0): minus = n - np.abs(minus)
# Store the coordinates
result_coord[count] = site_coord
result_coord[count][i] = minus
# Store the spin value
spin_index = np.where(np.all(result_coord[count]==coord,axis=1))[0][0]
result_spins[count] = spins[spin_index]
count = count + 1
# Store the coordinates
result_coord[count] = site_coord
result_coord[count][i] = plus
# Store the spin value
spin_index = np.where(np.all(result_coord[count]==coord,axis=1))[0][0]
result_spins[count] = spins[spin_index]
count = count + 1
我真的不知道该怎么做才能更快,但这会有很大帮助。也许是另一种存储一切的方式?在
不是答案,只是一些整理建议:当你试图记录计算的每一步时,会有大量的复制。在不牺牲这一点的情况下,您可以删除
site_coord_i
,然后这避免了中间步骤(“如果…”)。 另一个建议是推迟使用子阵列,直到您真正需要它:
^{pr2}$目标是减少比较中使用的变量的维数,并且更倾向于使用局部变量。在
相关问题 更多 >
编程相关推荐