正在模型[Python]

时间:2017-04-06 10:56:09

标签: python python-3.x physics montecarlo complex-networks

我正在尝试模拟Barabasi-Albert网络中的Ising相变,并尝试复制一些可观测量的结果,如磁化和能量,就像在Ising网格模拟中观察到的那样。但是,我在解释结果时遇到了麻烦:不确定物理是否错误或实施中是否存在错误。以下是最低工作示例:

import numpy as np 
import networkx as nx
import random
import math

## sim params

# coupling constant
J = 1.0 # ferromagnetic

# temperature range, in units of J/kT
t0 = 1.0
tn = 10.0
nt = 10.
T = np.linspace(t0, tn, nt)

# mc steps
steps = 1000

# generate BA network, 200 nodes with preferential attachment to 3rd node
G = nx.barabasi_albert_graph(200, 3)

# convert csr matrix to adjacency matrix, a_{ij}
adj_matrix = nx.adjacency_matrix(G)
top = adj_matrix.todense()
N = len(top)

# initialize spins in the network, ferromagnetic
def init(N):
    return np.ones(N)

# calculate net magnetization
def netmag(state):
    return np.sum(state)

# calculate net energy, E = \sum J *a_{ij} *s_i *s_j
def netenergy(N, state):
    en = 0.
    for i in range(N):
        for j in range(N):
            en += (-J)* top[i,j]*state[i]*state[j] 
    return en

# random sampling, metropolis local update
def montecarlo(state, N, beta, top):

    # initialize difference in energy between E_{old} and E_{new}
    delE = []

    # pick a random source node
    rsnode = np.random.randint(0,N)

    # get the spin of this node
    s2 = state[rsnode]

    # calculate energy by summing up its interaction and append to delE
    for tnode in range(N):
        s1 = state[tnode]
        delE.append(J * top[tnode, rsnode] *state[tnode]* state[rsnode])

    # calculate probability of a flip
    prob = math.exp(-np.sum(delE)*beta)

    # if this probability is greater than rand[0,1] drawn from an uniform distribution, accept it
    # else retain current state
    if prob> random.random():
        s2 *= -1
    state[rsnode] = s2

    return state

def simulate(N, top):

    # initialize arrays for observables
    magnetization = []
    energy = []
    specificheat = []
    susceptibility = []

    for count, t in enumerate(T):


        # some temporary variables
        e0 = m0 = e1 = m1 = 0.

        print 't=', t

        # initialize spin vector
        state = init(N)

        for i in range(steps):

            montecarlo(state, N, 1/t, top)

            mag = netmag(state)
            ene = netenergy(N, state)

            e0 = e0 + ene
            m0 = m0 + mag
            e1 = e0 + ene * ene
            m1 = m0 + mag * mag

        # calculate thermodynamic variables and append to initialized arrays
        energy.append(e0/( steps * N))
        magnetization.append( m0 / ( steps * N)) 
        specificheat.append( e1/steps - e0*e0/(steps*steps) /(N* t * t))
        susceptibility.append( m1/steps - m0*m0/(steps*steps) /(N* t *t))

        print energy, magnetization, specificheat, susceptibility

        plt.figure(1)
        plt.plot(T, np.abs(magnetization), '-ko' )
        plt.xlabel('Temperature (kT)')
        plt.ylabel('Average Magnetization per spin')

        plt.figure(2)
        plt.plot(T, energy, '-ko' )
        plt.xlabel('Temperature (kT)')
        plt.ylabel('Average energy')

        plt.figure(3)
        plt.plot(T, specificheat, '-ko' )
        plt.xlabel('Temperature (kT)')
        plt.ylabel('Specific Heat')

        plt.figure(4)
        plt.plot(T, susceptibility, '-ko' )
        plt.xlabel('Temperature (kT)')
        plt.ylabel('Susceptibility')

simulate(N, top)

观察到的结果

  1. Magnetization trend as a function of temperature
  2. Specific Heat
  3. 我已经尝试过大量注释代码,如果有什么我忽略了请问。

    问题

    1. 磁化趋势是否正确?随着温度的升高,磁化强度降低,但无法确定相变的临界温度。
    2. 随着温度的升高,能量接近于零,这与Ising网格中观察到的结果似乎是一致的。为什么我会得到负的比热值?
    3. 如何选择monte carlo步数?这只是基于网络节点数量的命中和试验吗?
    4. 编辑:02.06:simulation breaks down for anti-ferromagnetic configuration:反铁磁配置的仿真失效

1 个答案:

答案 0 :(得分:3)

首先,由于这是一个编程站点,让我们分析一下该程序。您的计算效率非常低,这使得探索更大的图形变得不切实际。在您的情况下,邻接矩阵是200x200(40000)元素,只有大约3%的非零。将其转换为密集矩阵意味着更多的计算,同时评估montecarlo例程中的能量差异和netenergy中的净能量。以下代码在我的系统上执行速度提高了5倍,预计更大的速度可以使用更大的图表:

# keep the topology as a sparse matrix
top = nx.adjacency_matrix(G)

def netenergy(N, state):
    en = 0.
    for i in range(N):
        ss = np.sum(state[top[i].nonzero()[1]])
        en += state[i] * ss
    return -0.5 * J * en

注意因子中的0.5 - 因为邻接矩阵是对称的,每对自旋都被计算两次!

def montecarlo(state, N, beta, top):
    # pick a random source node
    rsnode = np.random.randint(0, N)
    # get the spin of this node
    s = state[rsnode]
    # sum of all neighbouring spins
    ss = np.sum(state[top[rsnode].nonzero()[1]])
    # transition energy
    delE = 2.0 * J * ss * s
    # calculate transition probability
    prob = math.exp(-delE * beta)
    # conditionally accept the transition
    if prob > random.random():
        s = -s
    state[rsnode] = s

    return state

请注意转换能量中的因子2.0 - 代码中缺少它!

这里有一些numpy索引魔法。 top[i]是节点 i 的稀疏邻接行向量,top[i].nonzero()[1]是非零元素的列索引(top[i].nonzero()[0]是行索引,其中都是等于0,因为它是行向量)。因此state[top[i].nonzero()[1]]是节点 i 的相邻节点的值。

现在去物理学。热力学性质是错误的,因为:

e1 = e0 + ene * ene
m1 = m0 + mag * mag

应该是:

e1 = e1 + ene * ene
m1 = m1 + mag * mag

specificheat.append( e1/steps - e0*e0/(steps*steps) /(N* t * t))
susceptibility.append( m1/steps - m0*m0/(steps*steps) /(N* t *t))

应该是:

specificheat.append((e1/steps/N - e0*e0/(steps*steps*N*N)) / (t * t))
susceptibility.append((m1/steps/N - m0*m0/(steps*steps*N*N)) / t)

(你最好在早期平均能量和磁化力)

这使得热容量和对磁场的磁化率为正值。请注意敏感度分母中的单个t

现在该程序(希望)正确,让我们谈谈物理。对于每个温度,你从一个全向旋转状态开始,然后让它一次进化一个旋转。显然,除非温度为零,否则该初始状态远离热平衡,因此系统将开始向对应于给定温度的状态空间部分漂移。这个过程被称为热化,并且在此期间收集静态信息是没有意义的。您必须始终将模拟在给定温度下分成两部分 - 热化和实际显着运行。需要多少次迭代才能达到平衡?很难说 - 当它变得(相对)稳定时,使用能量的移动平均值并进行监控。

其次,更新算法每次迭代改变一次旋转,这意味着程序将非常缓慢地探索状态空间,并且您需要大量的迭代才能获得分区函数的良好近似。通过200次旋转,1000次迭代可能就够了。

其余的问题实际上并不属于这里。