IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 人工智能 -> 【Python分子动力学】 -> 正文阅读

[人工智能]【Python分子动力学】

1. 前言


分子动力学是一套分子模拟方法,该方法主要是依靠计算机来模拟分子、原子体系的运动,是一种多体模拟方法。通过对分子、原子在一定时间内运动状态的模拟,从而以动态观点考察系统随时间演化的行为。通常,分子、原子的轨迹是通过数值求解牛顿运动方程得到,势能(或其对笛卡尔坐标的一阶偏导数,即力)通常可以由分子间相互作用势能函数、分子力学力场、全始计算给出。对于考虑分子本身的量子效应的体系,往往采用波包近似处理或采用量子力学的费恩曼路径积分表述方式[1]处理。 分子动力学也常常被采用作为研究复杂体系热力学性质的采样方法。在分子体系的不同状态构成的系综中抽取样本,从而计算体系的构型积分,并以构型积分的结果为基础进一步计算体系的热力学量和其他宏观性质。 分子动力学最早在20世纪50年代由物理学家提出,如今广泛应用于物理、化学、生物体系的理论研究中。

1.1 分子热运动


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ikwlSeKR-1654083484608)(./Images/Translational_motion.gif)]

上图为一个分子系统热运动的模拟动画。其中一些小球被涂成了红色方便追踪。在这个模拟中,平均而言,两个分子碰撞前后动能保持不变。同时,我们忽视了黑体辐射,即系统的总能量保持不变。

1.2 理想气体模型


1.2.1 弹性碰撞

液体或者气体中分子之间发生的碰撞并不是完美的弹性碰撞。因为在碰撞的过程中,分子的平动会和其他运动自由度之间发生能量交换。但是平均而言,分子间的碰撞可以被简化为弹性碰撞,即分子间只发生平动动能交换。

我们考虑如下一个简化系统作为分子热运动的近似。

  1. 分子抽象为一个具有质量m和直径r的圆球。
  2. 分子间的相互作用力暂时被忽略。
  3. 当两个分子接触时,发生完全弹性碰撞。

1.2.2 二维分子体系的弹性碰撞

在这里插入图片描述

为了方便理解和作图,我们这里对二维情况下的弹性碰撞进行计算。对于两个无旋转的刚体而言,发生弹性碰撞时遵从动量守恒,能量守恒和角动量守恒。如果二者之间没有摩擦力,则二者速度在碰撞点切线方向上保持不变,碰撞只改变速度在垂直切线上的分量。

碰撞之后二者速度的表达式为:

在这里插入图片描述

上式中括号表示两个矢量的内积或者点乘。

1.3 理想气体分子动力学模拟


我们将使用理想气体模型,模拟Ar原子在特定温度下于二维平面上的热运动。

Ar原子的范德瓦尔斯半径为0.2 nm,因此可以粗略认为两个Ar原子在距离0.4 nm时发生了弹性碰撞。同时,当Ar原子距离容器壁距离小于0.2 nm时,我们认为其与容器壁发生了弹性碰撞。

这里设置如下初始条件:

  1. 所有分子的初始位置为随机值
  2. 所有分子的初始速率相同,速度方向为随机值
%matplotlib widget

import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
from matplotlib.animation import FuncAnimation

X, Y = 0, 1
class MDSimulation:

    def __init__(self, pos, vel, r, m):
        """
        Initialize the simulation with identical, circular particles of radius
        r and mass m. The n x 2 state arrays pos and vel hold the n particles'
        positions in their rows as (x_i, y_i) and (vx_i, vy_i).

        """
        self.pos = np.asarray(pos, dtype=float)
        self.vel = np.asarray(vel, dtype=float)
        self.n = self.pos.shape[0]
        self.r = r
        self.m = m
        self.nsteps = 0

    def advance(self, dt):
        """Advance the simulation by dt seconds."""
        self.nsteps += 1
        # Update the particles' positions according to their velocities.
        self.pos += self.vel * dt
        # Find indices for all unique collisions.
        dist = squareform(pdist(self.pos))
        iarr, jarr = np.where(dist < 2 * self.r)
        k = iarr < jarr
        iarr, jarr = iarr[k], jarr[k]

        # For each collision, update the velocities of the particles involved.
        for i, j in zip(iarr, jarr):
            pos_i, vel_i = self.pos[i], self.vel[i]
            pos_j, vel_j = self.pos[j], self.vel[j]
            rel_pos, rel_vel = pos_i - pos_j, vel_i - vel_j
            r_rel = rel_pos @ rel_pos
            v_rel = rel_vel @ rel_pos
            v_rel = 2 * rel_pos * v_rel / r_rel - rel_vel
            v_cm = (vel_i + vel_j) / 2
            self.vel[i] = v_cm - v_rel/2
            self.vel[j] = v_cm + v_rel/2

        # Bounce the particles off the walls where necessary, by reflecting
        # their velocity vectors.
        hit_left_wall = self.pos[:, X] < self.r
        hit_right_wall = self.pos[:, X] > 1 - self.r
        hit_bottom_wall = self.pos[:, Y] < self.r
        hit_top_wall = self.pos[:, Y] > 1 - self.r
        self.vel[hit_left_wall | hit_right_wall, X] *= -1
        self.vel[hit_bottom_wall | hit_top_wall, Y] *= -1

# Number of particles.
n = 1000
# Scaling factor for distance, m-1. The box dimension is therefore 1/rscale.
rscale = 5.e6
# Use the van der Waals radius of Ar, about 0.2 nm.
r = 2e-10 * rscale
# Scale time by this factor, in s-1.
tscale = 1e9    # i.e. time will be measured in nanoseconds.
# Take the mean speed to be the root-mean-square velocity of Ar at 300 K.
sbar = 432 * rscale / tscale
# Time step in scaled time units.
FPS = 30
dt = 1/FPS
# Particle masses, scaled by some factor we're not using yet.
m = 1

# Initialize the particles' positions randomly.
pos = np.random.random((n, 2))
# Initialize the particles velocities with random orientations and same magnitudes.
theta = np.random.random(n) * 2 * np.pi
s0 = sbar * np.ones(n)
vel = (s0 * np.array((np.cos(theta), np.sin(theta)))).T

sim = MDSimulation(pos, vel, r, m)

# Set up the Figure and make some adjustments to improve its appearance.
DPI = 100
width, height = 800, 400
fig = plt.figure(figsize=(width/DPI, height/DPI), dpi=DPI)
fig.subplots_adjust(left=0, right=0.97)
sim_ax = fig.add_subplot(121, aspect='equal', autoscale_on=False)
sim_ax.set_xticks([])
sim_ax.set_yticks([])
# Make the box walls a bit more substantial.
for spine in sim_ax.spines.values():
    spine.set_linewidth(2)

speed_ax = fig.add_subplot(122)
speed_ax.set_xlabel('Speed $v\,/m\,s^{-1}$')
speed_ax.set_ylabel('$f(v)$')

particles, = sim_ax.plot([], [], 'ko')
particles_color, = sim_ax.plot([], [], 'ro')

class Histogram:
    """A class to draw a Matplotlib histogram as a collection of Patches."""

    def __init__(self, data, xmax, nbars, density=False):
        """Initialize the histogram from the data and requested bins."""
        self.nbars = nbars
        self.density = density
        self.bins = np.linspace(0, xmax, nbars)
        self.hist, bins = np.histogram(data, self.bins, density=density)

        # Drawing the histogram with Matplotlib patches owes a lot to
        # https://matplotlib.org/3.1.1/gallery/animation/animated_histogram.html
        # Get the corners of the rectangles for the histogram.
        self.left = np.array(bins[:-1])
        self.right = np.array(bins[1:])
        self.bottom = np.zeros(len(self.left))
        self.top = self.bottom + self.hist
        nrects = len(self.left)
        self.nverts = nrects * 5
        self.verts = np.zeros((self.nverts, 2))
        self.verts[0::5, 0] = self.left
        self.verts[0::5, 1] = self.bottom
        self.verts[1::5, 0] = self.left
        self.verts[1::5, 1] = self.top
        self.verts[2::5, 0] = self.right
        self.verts[2::5, 1] = self.top
        self.verts[3::5, 0] = self.right
        self.verts[3::5, 1] = self.bottom

    def draw(self, ax):
        """Draw the histogram by adding appropriate patches to Axes ax."""
        codes = np.ones(self.nverts, int) * path.Path.LINETO
        codes[0::5] = path.Path.MOVETO
        codes[4::5] = path.Path.CLOSEPOLY
        barpath = path.Path(self.verts, codes)
        self.patch = patches.PathPatch(barpath, fc='tab:green', ec='k',
                                  lw=0.5, alpha=0.5)
        ax.add_patch(self.patch)

    def update(self, data):
        """Update the rectangle vertices using a new histogram from data."""
        self.hist, bins = np.histogram(data, self.bins, density=self.density)
        self.top = self.bottom + self.hist
        self.verts[1::5, 1] = self.top
        self.verts[2::5, 1] = self.top

def get_speeds(vel):
    """Return the magnitude of the (n,2) array of velocities, vel."""
    return np.hypot(vel[:, X], vel[:, Y])

def get_KE(speeds):
    """Return the total kinetic energy of all particles in scaled units."""
    return 0.5 * sim.m * sum(speeds**2)

speeds = get_speeds(sim.vel)
speed_hist = Histogram(speeds, 2.5 * sbar, 50, density=True)
speed_hist.draw(speed_ax)
speed_ax.set_xlim(speed_hist.left[0], speed_hist.right[-1])
# TODO don't hardcode the upper limit for the histogram speed axis.
ticks = np.linspace(0, 1000, 11, dtype=int)
speed_ax.set_xticks(ticks * rscale/tscale)
speed_ax.set_xticklabels([str(tick) for tick in ticks])
speed_ax.set_yticks([])

fig.tight_layout()

# The 2D Maxwell-Boltzmann equilibrium distribution of speeds.
mean_KE = get_KE(speeds) / n
a = sim.m / 2 / mean_KE
# Use a high-resolution grid of speed points so that the exact distribution
# looks smooth.
sgrid_hi = np.linspace(0, speed_hist.bins[-1], 200)
f = 2 * a * sgrid_hi * np.exp(-a * sgrid_hi**2)
mb_line, = speed_ax.plot(sgrid_hi, f, c='0.7')
# Maximum value of the 2D Maxwell-Boltzmann speed distribution.
fmax = np.sqrt(sim.m / mean_KE / np.e)
speed_ax.set_ylim(0, fmax)

# For the distribution derived by averaging, take the abcissa speed points from
# the centre of the histogram bars.
sgrid = (speed_hist.bins[1:] + speed_hist.bins[:-1]) / 2
mb_est_line, = speed_ax.plot([], [], c='r')
mb_est = np.zeros(len(sgrid))

# A text label indicating the time and step number for each animation frame.
xlabel, ylabel = sgrid[-1] / 2 + 0.1, 0.9 * fmax
label = speed_ax.text(xlabel, ylabel, '$t$ = {:.1f}s, step = {:d}'.format(0, 0))

def init_anim():
    """Initialize the animation"""
    particles.set_data([], [])
    particles_color.set_data([], [])

    return particles, particles_color, speed_hist.patch, mb_est_line, label

def animate(i):
    """Advance the animation by one step and update the frame."""
    global sim, verts, mb_est_line, mb_est
    sim.advance(dt)

    particles.set_data(sim.pos[:, X], sim.pos[:, Y])
    particles.set_markersize(1.0)
    particles_color.set_data(sim.pos[-5:, X], sim.pos[-5:, Y])
    particles_color.set_markersize(5.0)

    speeds = get_speeds(sim.vel)
    speed_hist.update(speeds)

    # Once the simulation has approached equilibrium a bit, start averaging
    # the speed distribution to indicate the approximation to the Maxwell-
    # Boltzmann distribution.
    if i >= IAV_START:
        mb_est += (speed_hist.hist - mb_est) / (i - IAV_START + 1)
        mb_est_line.set_data(sgrid, mb_est)

    label.set_text('$t$ = {:.1f} ns, step = {:d}'.format(i*dt, i))

    return particles, particles_color, speed_hist.patch, mb_est_line, label

# Only start averaging the speed distribution after frame number IAV_ST.
IAV_START = 250
# Number of frames; set to None to run until explicitly quit.
frames = 301
anim = FuncAnimation(fig, animate, frames=frames, interval=10, blit=False,
                    init_func=init_anim)

anim.save('Maxwell-BoltzmannDistribution.gif', writer='imagemagick', fps=10)

效果如下
请添加图片描述

from IPython.display import Image
Image(filename ='Maxwell-BoltzmannDistribution.gif', width=800)

在这里插入图片描述

经过一定时间演化,速率分布变化逐步减小,达到平衡状态。其中灰线为二维情况下Maxwell-Boltzmann速率分布函数:
f ( v ) = m v k B T exp ? ( ? m v 2 2 k B T ) f(v) = \frac{mv}{k_\mathrm{B}T}\exp\left(-\frac{mv^2}{2k_\mathrm{B}T}\right) f(v)=kB?Tmv?exp(?2kB?Tmv2?)

1.4 Lennard-Jones potential


The potential energy of the 12-6 Lennard-Jones potential is given as

V LJ ( r ) = 4 ε [ ( σ r ) 12 ? ( σ r ) 6 ] V_{\text{LJ}}(r)=4\varepsilon \left[\left({\frac {\sigma }{r}}\right)^{12}-\left({\frac {\sigma }{r}}\right)^{6}\right] VLJ?(r)=4ε[(rσ?)12?(rσ?)6]

σ \sigma σ is the radius where the potential is zero and is defined as the van der waals radius. ε \varepsilon ε is the energy minimum of the interaction (see the figure below).

We don’t want to compute long range interactions as they will be negligible. We therefore apply a cutoff past r σ = 2.5 \frac{r}{\sigma}=2.5 σr?=2.5. However, as the particles move past the cutoff distance there will be a small jump in the energy, which is not realistic, so we shift the potential so that the potential goes to zero at r σ = 2.5 \frac{r}{\sigma}=2.5 σr?=2.5.

Below is a plot of the Lennard-Jones potential with the shifted potential shown for comparison.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

r = np.linspace(0.01,3.0, 500) # Make a radius vector
epsilon = 1 # Energy minimum
sigma = 1 # Distance to zero crossing point
E_LJ = 4*epsilon*((sigma/r)**12-(sigma/r)**6) # Lennard-Jones potential

plt.figure(figsize=[6,6])
plt.plot(r, E_LJ, 'r-', linewidth=1, label=r" $LJ\; pot$") # Red line is unshifted LJ

# The cutoff and shifting value
Rcutoff = 2.5
phicutoff = 4.0/(Rcutoff**12)-4.0/(Rcutoff**6) # Shifts the potential so at the cutoff the potential goes to zero

E_LJ_shift = E_LJ - phicutoff # Subtract the value of the potential at r=2.5

plt.plot(r[r < 2.5], E_LJ_shift[r < 2.5], 'b-', linewidth=1, label=r"$LJ\; pot\; shifted$") # Blue line is shifted

#Plot formatting
plt.axhline(0, color='grey', linestyle='--', linewidth=2)
plt.axvline(1, color='grey', linestyle='--', linewidth=2)
plt.xlim([0.0, 3.0])
plt.ylim([-1, 1])
plt.ylabel(r"$E_{LJ}/\epsilon$", fontsize=20)
plt.xlabel(r"$r/\sigma$", fontsize=20)
plt.legend(frameon = False, fontsize=20)
plt.title(r"$Lennard-Jones \; potential$", fontsize=20)

在这里插入图片描述

1.5 Periodic boundary conditions


Periodic boundary conditions allow for an approximation of an infinitely sized system by simulating a simple unit cell. This is illustrated below. The black box is the only cell we simulate; the tiled images around it are there for illustration. The green particle moves past the top boundary of the unit cell and are moved to the bottom of the box with the same velocity (illustrated by the red dashed line). This boundary condition keeps the volume and number of particles constant in the simulation.

1.6 Reduced units


By choosing our units we can remove any constants and get a general behaviour for all gases. Mass, sigma, epsilon and the Boltzmann constant are set to equal one. Reduced coordinates are used for the other variables which are derived from the parameters set to one.
x ? = x σ x^{*} = \frac{x}{\sigma} x?=σx?
v ? = v t ? σ v^{*} = v\frac{t^{*}}{\sigma} v?=vσt??
t ? = t ( ? m σ 2 ) 1 / 2 t^{*} = t\left(\frac{\epsilon}{m \sigma^{2}} \right)^{1/2} t?=t(mσ2??)1/2
E ? = E ? E^{*} = \frac{E}{\epsilon} E?=?E?
F ? = f σ ? F^{*} = f\frac{\sigma}{\epsilon} F?=f?σ?
P ? = P σ 3 ? P^{*} = P \frac{\sigma^{3}}{\epsilon} P?=P?σ3?
ρ ? = ρ σ d i m e n s i o n s \rho^{*} = \rho \sigma^{dimensions} ρ?=ρσdimensions
T ? = T k b ? T^{*} = T \frac{k_{b}}{\epsilon} T?=T?kb??

Where k b k_{b} kb? is Boltzmann’s constant.

This may seem complicated but it allows all of the equations to be written very simply in the program. This also gives us physical insight - for example, the reduced temperature is the ratio of the thermal energy k B T k_{B} T kB?T to the energy of the intermolecular interactions ? \epsilon ?.
Periodic boundary conditions

1.7 Calculating the forces


As mentioned above, the forces between particles can be calculated from the derivative/gradient of their potential energy. F = ? 1 r ? E ( r ) \textbf{F}=-\frac{1}{r}\nabla E(\textbf{r}) F=?r1??E(r) (in spherical coordinates)

F = ? 1 r ? E L J ( r ) = ? 1 r d E L J d r = ? 24 [ 2 ( σ r ) 14 ? ( σ r ) 8 ] \textbf{F} = -\frac{1}{r}\nabla E_{LJ}(\textbf{r}) = -\frac{1}{r}\frac{d E_{LJ}}{d \textbf{r}} = -24\left[2\left(\frac{\sigma}{\textbf{r}}\right)^{14} - \left(\frac{\sigma}{\textbf{r}}\right)^{8}\right] F=?r1??ELJ?(r)=?r1?drdELJ??=?24[2(rσ?)14?(rσ?)8]

Periodic boundary conditions have to be considered when we compute the forces between particles because a particle near the boundary of the unit cell has to be able to feel the force from a particle on the other side of the unit cell. For example, the pink particle above will feel the force from the green particle, even though they are far from each other because they are near opposite boundaries.

In order to easily implement periodic boundary conditions, scaled box units are used so that the particle positions are always between -0.5 and 0.5. If the distance between the particles is greater than half the scaled box units, the interaction with the particle in the next box are consider

def Compute_Forces(pos, acc, ene_pot, epsilon, BoxSize, DIM, N):
    # Compute forces on positions using the Lennard-Jones potential
    # Uses double nested loop which is slow O(N^2) time unsuitable for large systems
    Sij = np.zeros(DIM) # Box scaled units
    Rij = np.zeros(DIM) # Real space units

    #Set all variables to zero
    ene_pot = ene_pot*0.0
    acc = acc*0.0
    virial = 0.0

    # Loop over all pairs of particles
    for i in range(N-1):
        for j in range(i+1,N): #i+1 to N ensures we do not double count
            Sij = pos[i,:]-pos[j,:] # Distance in box scaled units
            for l in range(DIM): # Periodic interactions
                if (np.abs(Sij[l])>0.5):
                    Sij[l] = Sij[l] - np.copysign(1.0,Sij[l]) # If distance is greater than 0.5  (scaled units) then subtract 0.5 to find periodic interaction distance.

            Rij = BoxSize*Sij # Scale the box to the real units in this case reduced LJ units
            Rsqij = np.dot(Rij,Rij) # Calculate the square of the distance

            if(Rsqij < Rcutoff**2):
                # Calculate LJ potential inside cutoff
                # We calculate parts of the LJ potential at a time to improve the efficieny of the computation (most important for compiled code)
                rm2 = 1.0/Rsqij # 1/r^2
                rm6 = rm2**3.0 # 1/r^6
                rm12 = rm6**2.0 # 1/r^12
                phi = epsilon*(4.0*(rm12-rm6)-phicutoff) # 4[1/r^12 - 1/r^6] - phi(Rc) - we are using the shifted LJ potential
                # The following is dphi = -(1/r)(dV/dr)
                dphi = epsilon*24.0*rm2*(2.0*rm12-rm6) # 24[2/r^14 - 1/r^8]
                ene_pot[i] = ene_pot[i]+0.5*phi # Accumulate energy
                ene_pot[j] = ene_pot[j]+0.5*phi # Accumulate energy
                virial = virial + dphi*np.sqrt(Rsqij) # Virial is needed to calculate the pressure
                acc[i,:] = acc[i,:]+dphi*Sij # Accumulate forces
                acc[j,:] = acc[j,:]-dphi*Sij # (Fji=-Fij)

    return acc, np.sum(ene_pot)/N, -virial/DIM # return the acceleration vector, potential energy and virial coefficient

1.8 Temperature


Temperature is a macroscopic quantity. Microscopically it is less well defineddue to the low number of particles. However, if we use the kinetic energy of the parameters we can calculate the temperature.
E K = 1 2 m v 2 E_{K}=\frac{1}{2} mv^{2} EK?=21?mv2 k B T = 2 3 ∑ N E K k_{B} T = \frac{2}{3}\sum_{N}E_{K} kB?T=32?N?EK?

Where we sum over all $N $ atoms. We will use this in order to scale the velocities to maintain a constant temperature (remember we are using reduced units so k B = 1 k_{B}=1 kB?=1 and m = 1 m=1 m=1).

The function below calculates the temperature given the velocity of the atoms/particles.

def Calculate_Temperature(vel,BoxSize,DIM,N):
    ene_kin = 0.0
    for i in range(N):
        real_vel = BoxSize*vel[i,:]
        ene_kin = ene_kin + 0.5*np.dot(real_vel,real_vel)

    ene_kin_aver = 1.0*ene_kin/N
    temperature = 2.0*ene_kin_aver/DIM

    return ene_kin_aver,temperature

1.9 Molecular dynamics program


The molecular dynamics program contains the instructions for the computer to use to move the particles/atoms through time. Most often this is written in Fortran and C; these compiled languages are orders of magnitude faster than Python, however a scripting language like Python is helpful to provide understanding about how molecular dynamics is implemented.

The main steps in a molecular dynamics simulation are:

  1. Initialise the position of particles
  2. Calculate the pairwise forces on the particles by calculating the gradient of the potential energy $ F = \nabla E(\textbf{r})=1/r\partial E(\textbf{r})/\partial r$
  3. Compute the new positions by integrating the equation of motion (we will use the velocity Verlet algorithm)
  4. Apply a thermostat to maintain the temperature at the set value (we will use the velocity scaling for temperature control)
  5. Go back to step 2, recompute the forces and continue until the maximum number of steps

1.9.1 Initialising the particles

import numpy as np

DIM = 2 # Dimensions
N = 32

BoxSize = 8.0

volume  = BoxSize**DIM
density = N / volume
print("volume = ", volume, " density = ", density)

pos = np.random.rand(N, DIM)

MassCentre = np.sum(pos,axis=0)/N

for i in range(DIM):
    pos[:,i] = pos[:,i]-MassCentre[i]

在这里插入图片描述

1.9.2 Integrating the equations of motion

We will make use of the velocity Verlet integrator which integrates Newton’s equations of motion in 1D:
d x d t = v ?? a n d ?? d v d t = d F ( x ) m \frac{dx}{dt}=v\; and \; \frac{dv}{dt}=\frac{dF(x)}{m} dtdx?=vanddtdv?=mdF(x)?

The velocity Verlet algorithm spilts the velocity update into two steps intially doing a half step then modifing the acceleration and then doing the second velocity update. Written in full, this gives:

  1. Calculate x ( t + Δ t ) = x ( t ) + v ( t + 1 2 ) Δ t x(t+\Delta t) = x(t)+v\left(t+\frac{1}{2}\right)\Delta t x(t+Δt)=x(t)+v(t+21?)Δt
  2. Calculate $v\left(t+\frac{1}{2}\Delta t\right)= v(t)+\frac{1}{2}a(t)\Delta t $
  3. Derive a ( t + Δ t ) a(t+\Delta t) a(t+Δt) from the interaction potential using x ( t + Δ t ) x(t+\Delta t) x(t+Δt)
  4. Calculate v ( t + Δ t ) = v ( t + 1 2 ) + 1 2 a ( t + Δ t ) Δ t v(t+\Delta t)=v\left(t+\frac{1}{2}\right)+\frac{1}{2}a(t+\Delta t) \Delta t v(t+Δt)=v(t+21?)+21?a(t+Δt)Δt

Between step 1 and 2 we rescale the velocities to maintain the temperature at the requested value.

The output is saved in the same folder as the ipython notebook as traj.xyz and can be opened by Avogadro or VMD.

# Main MD loop
def MD(pos, NSteps, deltat, TRequested, DumpFreq, epsilon, BoxSize, DIM):

    # Vectors to store parameter values at each step
    N = np.size(pos[:,1])
    ene_kin_aver = np.ones(NSteps)
    ene_pot_aver = np.ones(NSteps)
    temperature = np.ones(NSteps)
    virial = np.ones(NSteps)
    pressure = np.ones(NSteps)
    ene_pot = np.ones(N)

    vel = (np.random.randn(N,DIM)-0.5)
    acc = (np.random.randn(N,DIM)-0.5)

    # Open file which we will save the outputs to
    f = open('traj.xyz', 'w')

    for k in range(NSteps):
        # Refold positions according to periodic boundary conditions
        for i in range(DIM):
            period = np.where(pos[:,i] > 0.5)
            pos[period,i]=pos[period,i]-1.0
            period = np.where(pos[:,i] < -0.5)
            pos[period,i]=pos[period,i]+1.0

        # r(t+dt) modify positions according to velocity and acceleration
        pos = pos + deltat*vel + 0.5*(deltat**2.0)*acc # Step 1

        # Calculate temperature
        ene_kin_aver[k],temperature[k] = Calculate_Temperature(vel,BoxSize,DIM,N)

        # Rescale velocities and take half step
        chi = np.sqrt(TRequested/temperature[k])
        vel = chi*vel + 0.5*deltat*acc # v(t+dt/2) Step 2

        # Compute forces a(t+dt),ene_pot,virial
        acc, ene_pot_aver[k], virial[k] = Compute_Forces(pos,acc,ene_pot,epsilon,BoxSize,DIM,N) # Step 3

        # Complete the velocity step 
        vel = vel + 0.5*deltat*acc # v(t+dt/2) Step 4

        # Calculate temperature
        ene_kin_aver[k],temperature[k] = Calculate_Temperature(vel,BoxSize,DIM,N)

        # Calculate pressure
        pressure[k]= density*temperature[k] + virial[k]/volume

        # Print output to file every DumpFreq number of steps
        if(k%DumpFreq==0): # The % symbol is the modulus so if the Step is a whole multiple of DumpFreq then print the values
            f.write("%s\n" %(N)) # Write the number of particles to file
            # Write all of the quantities at this step to the file
            f.write("Energy %s, Temperature %.5f\n" %(ene_kin_aver[k]+ene_pot_aver[k],temperature[k]))
            for n in range(N): # Write the positions to file
                f.write("X"+" ")
                for l in range(DIM):
                    f.write(str(pos[n][l]*BoxSize)+" ")
                f.write("\n")
            if(DIM==2):
                scatter.x = pos[:,0]*BoxSize
                scatter.y = pos[:,1]*BoxSize
                time.sleep(0.1)
        #print(ene_kin_aver[k], ene_pot_aver[k], temperature[k], pressure[k]) 

    f.close() # Close the file

    return ene_kin_aver, ene_pot_aver, temperature, pressure, pos

在这里插入图片描述

from bqplot import pyplot as plt
import time

# Setting up the simulation
NSteps = 5000 # Number of steps
deltat = 0.0032 # Time step in reduced time units
TRequested = 0.5# #Reduced temperature
DumpFreq = 100 # Save the position to file every DumpFreq steps
epsilon = 1.0 # LJ parameter for the energy between particles

figure = plt.figure(title='Molecular Dynamics')
figure.layout.width = '600px'
figure.layout.height = '600px'

scatter = plt.scatter(pos[:,0]*BoxSize, pos[:,1]*BoxSize)

plt.xlim(-0.5*BoxSize, 0.5*BoxSize)
plt.ylim(-0.5*BoxSize, 0.5*BoxSize)
plt.show()
ene_kin_aver, ene_pot_aver, temperature, pressure, pos = MD(pos,NSteps,deltat,TRequested,DumpFreq,epsilon,BoxSize,DIM)
import matplotlib.pyplot as plt

# Plot all of the quantities
def plot():
    plt.figure(figsize=[7,12])
    plt.rc('xtick', labelsize=15) 
    plt.rc('ytick', labelsize=15)
    plt.subplot(4, 1, 1)
    plt.plot(ene_kin_aver[1000:],'k-')
    plt.ylabel(r"$E_{K}$", fontsize=20)
    plt.subplot(4, 1, 2)
    plt.plot(ene_pot_aver[1000:],'k-')
    plt.ylabel(r"$E_{P}$", fontsize=20)
    plt.subplot(4, 1, 3)
    plt.plot(temperature[1000:],'k-')
    plt.ylabel(r"$T$", fontsize=20)
    plt.subplot(4, 1, 4)
    plt.plot(pressure[1000:],'k-')
    plt.ylabel(r"$P$", fontsize=20)
    plt.show()

plot()

在这里插入图片描述
在这里插入图片描述

参考文献来自桑鸿乾老师的课件:科学计算和人工智能
特此鸣谢!!!

  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2022-06-06 17:19:25  更:2022-06-06 17:20:13 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 2:35:41-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码