我用一个简单的编码结构来模拟尺寸大于3的铁磁体的Ising Model,但是在效率上有一些问题。在我的代码中,有一个特定的函数是瓶颈。
在模拟过程中,需要找到一个给定站点的最近邻。例如,在二维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,然后

    # New coords, implement periodic boundaries
    plus = (site_coord[i] + neighbor_coupling) % n
    minus = (site_coord[i] - neighbor_coupling + n) % n

这避免了中间步骤(“if…”)。
另一个建议是推迟使用子阵列,直到您真正需要它:
    # Store the coordinates
    rcc = site_coord
    rcc[i] = plus
    # Store the spin value
    spin_index = np.where(np.all(rcc==coord,axis=1))[0][0]
    result_spins[count] = spins[spin_index]
    result_coord[count] = rcc
    count += 1

其目的是减少比较中使用的变量的维数,并选择局部变量。

09-27 00:21