You are on page 1of 100

Problems and Solutions

Molecular Simulations Methods in


Mechanics and Physics

Dibakar Datta
Brown University, Providence, USA

Sang-Pil Kim
Samsung Electronics, Seoul, South Korea

Vivek B Shenoy
The University of Pennsylvania, Philadelphia, USA
Contents
1 Random Numbers and Molecular Simulations ………………………….... 3

2 Use of Monte Carlo Methods to Do Some Integrals ………………………. 8

3 Use of Monte Carlo Methods for Evaluation of Thermodynamics


Properties of One Multistate System ……………………………………....13

4 Use of Monte Carlo Methods to Evaluate the Thermodynamics Properties


of the One Dimensional Ising Model ………………………………………18

5 Use of Monte Carlo Methods to Evaluate the Thermodynamics Properties


of the Two Dimensional Ising Model …………………………………… 23

6 Kinetic Monte Carlo Method for Langmuir Adsorption-Desorption


Problem ……………………………………………………………………. 27

7 Molecular Dynamics for Simple LJ (Two & Three Dimensional Particles)


Systems ........................................................................................................... 30

8 Computation of Pressure and Radial Distribution Function Using


LAMMPS …………………………………………………………………... 38

9 Computation of Diffusivity and Thermal Conductivity Using LAMMPS 41

10 Indentation Using LAMMPS ………………………………………………43

Appendix A Matlab Code for Chapter 1 ………………………………... 44


Appendix B Matlab Code for Chapter 2 ………………………………... 47
Appendix C Matlab Code and Data File for Chapter 3 ………………... 51

! 1!
Appendix D Matlab Code for Chapter 4 ………………........................... 60
Appendix E Matlab Code for Chapter 5 ………………............................ 65
Appendix F Matlab Code for Chapter 6 ………………............................ 73
Appendix G Lammps Script for Chapter 7 ……………………………... 80
Appendix H Lammps Script and Matlab Code for Chapter 8 ………… 86
Appendix I Lammps Script and Matlab Code for Chapter 9 ………….. 94
Appendix J Lammps Script and Matlab Code for Chapter 10 ………… 98
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!

! 2!
!

1
Random Numbers and Molecular Simulations
Problem 1.1
Generate 4 million random numbers uniformly distributed between 0 and 1.
Compute their mean by distributing them into 100. Estimate the error on the
mean and see if it agrees with the deviation of the computed mean from 0.5. Now
distribute them into 1000 bins and repeat the procedure.

Procedure of ‘binning’

Take the N events and break them into m sets or ‘bins’ of n = N/m events each (make
sure N/m is an integer). Find the mean of the numbers in each of these m bins; let
these means be xi , i =1,2,…,m. If the central limit theorem holds, the distribution of
xi’s should be Gaussian. Moreover, the uncertainty in the mean of these means, i.e.,
in

1 m
x = ∑ xi (1.1)
m i=1
is expected to be

δx = (x 2
− x
2
) / ( m − 1) (1.2)

where
1 m 2
x 2
= ∑ xi (1.3)
m i=1
If m is a large number, we may with very little error replace m-1 by m in this
equation.
Let’s see how that works for the numbers produced by the generator. We have a lot
of latitude in the choice of m. So long as N/m is large enough for the central limit
theorem to come into play, all such choices should give much the same value for δx.
Also, δx should be comparable, provided the generator is good, to the difference
! 3!
between < x > and ½ . What does that mean? It means that roughly two-thirds of the
time, δx will be larger than the absolute difference between < x > and ½; the rest of
the time the difference will be larger than δx, but not dramatically larger. One to two
times as large will be common; two to three times as large will certainly occur but
not more than a few percent of the time; and more than three times as large will be
rare.

No of Bin Deviation With Error with Bin Deviation Error Without Analytical
Bin Without Bin Bin Error
100 0.000215 0.000144 0.000215 0.000144 0.000215
1000 0.000078 0.000145 0.000078 0.000144 0.000144

Table 1.1 Estimation of error on the mean with and without binning
!
!
Problem 1.2
Find a random number generator which claims to produce evenly distributed
random numbers on the interval [0,1] or (0,1). Run a test of the generator in
which you generate N random numbers with N around ten million and see how
they are distributed by dividing the interval into ten subintervals of equal size.
Determine the fraction of the numbers in each subinterval and also the
uncertainty in this number.
Determine the latter by dividing the run up into ten parts (often called “bins"),
finding, for each subinterval, the number of events in each bin and then
computing, for each subinterval, the mean and the variance of these numbers.
Look at the correlations in the sequence of numbers; that is evaluate, for n
between 0 and 20
1 N 1 N
χ ( n ) = ∑ ( xi+n − x )( xi − x ) = N ∑ xi+n xi − ( x )
2

N i=1 (1.4)
i=1

using periodic boundary conditions, meaning x N + j ≡ x j . Notice that

1 N
χ ( 0 ) = ∑ ( xi − x )( x − x ) = x2 − ( x )
2

N i=1
i (1.5)

is the variance of x. Normalize the correlation function so that χ ( 0 ) = 1 .

! 4!
On the basis of your results, does the generator appear to be working, as it
should?
We have considered 1 million numbers for the speed of computing. !

!
Figure 1.1 The distribution of random numbers in ten subintervals of equal interval

Bin No 1 2 3 4 5 6 7 8 9 10
0.100122 0.099599 0.099753 0.100115 0.099969 0.099820 0.100057 0.100257 0.099806 0.100502
Fraction

Table 1.2 Fraction of the numbers in each subinterval

!
Bin No 1 2 3 4 5 6 7 8 9 10
100122 99599 99753 100115 99969 99820 100057 100257 99806 100502
No. of
Events
0.049953 0.149975 0.249852 0.349914 0.450019 0.550229 0.649917 0.749936 0.849850 0.949997
Mean
Variance 0.000833 0.000832 0.000832 0.000831 0.000837 0.000832 0.000831 0.0008309 0.000836 0.000836
!
Table 1.3 Uncertainty quantification of the random numbers

! 5!
n correlation
0 1
1 0.000020259813097612
2 0.000011675673976863
3 -0.000060191483037431
4 0.000021630773839709
5 -0.000141177154716232
6 -0.000044922519324975
7 0.000102002320232830
8 -0.000013534856363240
9 0.000073100502788581
10 0.000071693236619486
11 0.000029834616016466
12 -0.000059281554875223
13 0.000249376029785864
14 0.000008373749979362
15 -0.000041418950919470
16 0.000017963205148352
17 -0.000063381333307910
18 -0.000011930398607751
19 0.000184709093162316
20 0.000080121154401480

Table 1.4 Estimation of correlation of random numbers


!
We can observe that except χ (0) , all other correlations are close to zero. Hence the
random numbers generated are not correlated. So the generator appears to be
working, as it should be.

Problem 1.3
Consider n random numbers x1, x2…. xn that follow the probability distribution
1 1
p( x) = , −∞≤ x≤∞ (1.6)
π 1+ x 2
If the mean of the distribution computed from these numbers is

1 n
µ n = ∑ xi
n i=1 (1.7)

derive an expression for the probability distribution of µn .


!

! 6!
The given distribution is the Cauchy Distribution with Location Parameter ( x0 = 0 )

and Scale Parameter ( γ = 1 ). The n random numbers x1 , x2 ... xn follow this


distribution. If x is a Cauchy distributed random variable, the characteristic function
of the Cauchy distribution can be written as:

φx (t ) = E ( e ixt
) = ∫ f ( x )e ixt
dx = e− t (1.8)
−∞

This is the Fourier Transform of the probability density. We can express the original
probability density in terms of the characteristic function1 by using the Inverse
Fourier Transform:
1 ∞
f ( x) = ∫ φ X ( t ) e−ixt dt (1.9)
2π −∞

Equation 1.6 gives the mean of the distribution computed from these numbers. The
Characteristic Function of the sample mean can be written as:
n
⎛ i1 n ⎞ ⎛ −i ⎞
φ µn ( t ) = E ( e i µnt
) = E ⎜ e n ∑ xi t ⎟ = ⎜ e n ⎟ = e − t (1.10)
⎝ i=1 ⎠ ⎝ ⎠

The probability distribution of µn is also Cauchy Distribution.


!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1! The characteristic function is not differential at the origin because the Cauchy distribution does

not have an expected value.!


! 7!
2
Use of Monte Carlo Methods to Do Some
Integrals
!
!
Problem 2.1
Use Monte Carlo methods to find the natural logarithm of 2. Also, determine the
uncertainty in your result and make a comparison with a precise value of the
logarithm.

In order to evaluate the value of natural logarithm of 2, we perform the integral:


!
2 1
I=∫ dx (2.1)
1 x
!
The precise value of the logarithm: 0.693147181

No of bin No of points Result Uncertainty Percentage


per bin Error
100 10000 0.6932258 1.345481e-04 0.011342
100 100000 0.6931653 4.988322e-05 0.0026140

Table 2.1 Evaluation of natural logarithm of 2

Problem 2.2
Use Monte Carlo methods to do the integrals

⎡ 10 ⎤ ⎡ ⎛ ⎞⎤
10


2
I=∫ Πdx
⎢⎣ i=1 i ⎥⎦ ⎢ ⎜⎝
sin π nx n⎟ ⎥ (2.2)
1
⎣ n=1 ⎠⎦

No of bin No of points per bin Result Uncertainty


100 1000 0.0003951843 2.277833e-03
!
Table 2.2 Evaluation of 10 dimensional integral using MC Method

!
!

! 8!
Problem 2.3
Use importance sampling (not the random walk procedure) to do the integral
∞ e− x
I=∫ dx (2.3)
1
1+ 2sin 2 x
Use importance sampling according to the random walk procedure to do the
same integrals. Find the uncertainty in your results.

Importance and Random Sampling


Consider the following example in one dimension:

I = f = ∫ dx f ( x ) Q ( x ) = ∫ dx F ( x ) (2.4)

where Q(x) is a probability distribution. We may apply the method just learned to the
evaluation of this integral by generating a set of random numbers uniformly on the
integral over which the integral is taken and adding up the values of F(x) at these
points. But suppose that Q(x) is zero or close to zero on a large part of the interval
and that it is much larger on some small part of the interval, while f(x) varies
relatively little. Then it would be more efficient to sample the integrand in the range
of x where Q is large while largelt ignoring the range of x where Q is very small. A
way to do that is to generate a sequence of x’s distributed not uniformly on some
interval but rather according to the distribution Q(x). That is, one wants the number
of elements in the sequence which fall into an interval dx around x to be proportional
to Q(x)dx. Given such a sequence with elements xi , i =1,2,…,N , an approximation to
f is obtained from (assuming Q is normalized to unity)
1
f = ∑ f ( xi )
N i
(2.5)

The approximation improves with increasing N. In practice, there are cases for which
this approach doesn’t work well. If f is too wildly varying or becomes very large in
places where Q is small, it will not give good answers within a reasonable amount, or
perhaps within any amount, of computer time. Of course the same can be said of any

! 9!
kind of Monte Carlo evaluation of integrals.
Let’s look at a sample example,

1
I = ∫ dx x 2 e− x (2.6)
20

The probability distribution is Q ( x ) = exp ( −x ) , so we need to generate a sequence of


numbers distributed in this way. There are generators of this kind available in
standard software packages, but we can easily make one from a generator, which
produces a uniform distribution on the interval [0,1].
Consider two distinct distributions P(u) and Q(x) ans ask what is the relation between
x and u if the probability in dx around some x is to be the same as that in du around u.
Let that relation be u = u(x). Thus we write
P ( u ) du = Q ( x ) dx (2.7)
and if we can integrate both sides of this expression we will be able to use the result
to find u(x). The particular normalized distributions we have are
P ( u ) = 1 on [ 0,1] and Q ( x ) = e− x for all x > 0 (2.8)
Thus we consider
du = e− x dx (2.9)
which may be integrated to give

u = −e− x + C (2.10)
where C is a constant. If u = 0 is to coincide with x = 0, then C = 1 and

1− u = e− x or x = − log (1− u ) (2.11)


Thus we simply employ the usual generator to give a set of u’s uniformly distributed
on [0,1] and turn them into a set of x’s distributed according to exp(-x) by means of
the preceding formula. We take that set and evaluate
1 N 2
I MC = ∑ xi 2
N i=1 (2.12)

the result should be close to I. That’s been done for a set of one million x’s (or u’s)
broken into 100 bins for purposes of finding the uncertainty in the mean. The result is
IMC = 1.0011±0.0024 which is quite reasonable in all respects.
! 10!
E = ∑ Ei e− β Ei ∑e −βEj
(2.13)
i j

the sums being over all states of the system. We can’t possibly sum over all the states
of a many-particle system, but we can make an approximate evaluation of E using
the MC method. At a finite temperature, there will likely be many contributions to
the sums. Consequently, it is much more efficient to proceed by generating a
sequence of N states with energies distributed according to the Boltzmann
distribution. For that sequence of states,
1
E = ∑ Ei ≈ E
N i (2.14)

At least one hopes that E will approximate E.

The first question is how to generate such a sequence of states. In the example given
above, it was easy to generate the sequence of x’s because we could integrate the
probability distribution to find the necessary relation between x and u and a simple
random number generator gave us a good set of u’s. Usually it isn’t that simple, and
one must generate the x’s (or states) some other way. One way is to use a biased
random walk. Let’s look at a specific example, which is to evaluate a one-
dimensional integral,

I= ∫ dx f ( x ) P ( x )
−∞
(2.15)

I is the mean value of f over the probability distribution P; for definiteness, let
1 − x 2 /2
P( x) = e (2.16)

a Gaussian distribution. Now consider the sequence of x’s produced in a random
walk which starts at some plausible value of x, such x = 0, and in which the size of
the attempted steps is uniformly distributed between preset limits, say –a < δx < a
with a on the order of the distribution’s width i.e., around unity. The basic procedure
is as follows: Given that at the ith step the position is xi, one generates a random
number δx on the interval [-a,a] and considers a move to the position x′ = xi + δ x . If,
P ( x ′ ) > P ( xi ) , the move is accepted and if P ( x′ ) < P ( xi ) , one accepts the move with a

! 11!
probability P ( x′ ) / P ( xi ) . The latter is achieved by generating a random number on
the interval [0,1] and accepting the move if that random number is smaller than
P ( x ′ ) / P ( xi ) . If the move is accepted, xi+1 is set equal to x ′ ; and if the move is not

accepted, xi+1 is set equal to xi. In this way, one generates a set of x’s which will be
distributed according to the probability distribution P(x); that is, the number of points
in the sequence in the interval dx around x will be proportional to P(x)dx and so one
gets an approximation to I by using these points to evaluate
1 N
I MC = ∑ f ( xi )
N i=1
(2.17)

For example, let f ( x ) = x 2 and let N be one million. To get a measure of the
uncertainty of the mean, subdivide the simulation into one hundred bins. Also, start
from x1 = 0 and let a =1. One such run (a typical one) gives I = 0.9991±0.0048; the
exact answer is unity.
Now let’s solve the Problem 2.3.
!
No of Bin No of points per Result Uncertainty
bin
100 10000 0.7884821 1.514067e-04
!
Table 2.3 Evaluation of integral using Importance Sampling Method

No of Bin No of points per Result Uncertainty


bin
100 10000 0.7813938 4.867925e-04
!
Table 2.4 Evaluation of integral using Random Walk Method
!
!
!
!
!
!
!
!
!
!
!
!

! 12!
3
Use of Monte Carlo Methods for Evaluation
of Thermodynamic Properties of One Multi-
State System
Problem 3.1

Consider an object (a spin, or a segment of a step on a crystal surface with two


types of kinks, if you like), which has three internal states with energies εn= (n-
1)Δ, where n = 1,2,3, and Δ is a constant energy. It is a straightforward matter to
evaluate the mean energy and specific heat of this system at a temperature T
from the partition function, which is
3
Z (T ) = ∑ e− ε n /kT (3.1)
n=1

If one does that and tabulates the results, one finds the information given in the
file a004.dat given in the appendix. Temperatures are in units of Δ/k; energies, in
units of!Δ; and specific heats, in units of k (Boltzmann's constant). (Try to obtain
this data on your own)

Mean Energy: The Mean Energy of the system is given by

ε=
∑εe i i
− βε i

(3.2)
∑e i
− βε i

Specific Heat: The Specific Heat of the system is given by

⎡ ε2 − ε 2⎤
C=⎣ 2

(3.3)
kT

! 13!
Figure 3.1 Comparison of Energy and Specific Heat with the reference value

Problem 3.2

Alternatively, one may compute the energy and heat capacity by Monte Carlo
methods. Do that for an appropriate set of temperatures using the method of
importance sampling. Start from any of the three states and let the system make
a biased random walk through the states. Do the latter as follows: At any given
point in the simulation, the system is in some state i. Now attempt a move to
another state j. First, pick, with equal probability, either of the other two states
as the one ( j ) ! to which move is to be attempted. Accept that move with

probability unity if ε j < ε i and exp ⎡⎣ − ( ε j − ε i ) / kT ⎤⎦ if ε j > ε i . Accumulate the energy

and squared energy of the system after each attempted step; remember, if the
attempted move is rejected, the system remains in the state i and the energy and
squared energies of this state are added to the corresponding sums. Use a
reasonable number of steps (your choice) in this biased random walk and bin
the results for purposes of computing uncertainties in the energy and heat

! 14!
capacity.
From your simulation find the mean energy and the specific heat of the system
as functions of T. Find also the uncertainties. Find the specific heat two ways:
First, use the fluctuation expression,

C = ⎡⎣ ε 2 − ε ⎤⎦ / kT 2
2
(3.4)

where ε is the mean value of the energy and ε 2 is the mean value of the
squared energy; second, take the temperature derivative of the energy
numerically; that is,

∂U U (T + ∂T ) − U (T − ∂T )
C (T ) = ≈ (3.5)
∂T 2 ∂T

where U is the thermodynamic energy which is the same, in principle , as ε .


Plot your results along with the "exact" results from the data file a004.dat (in
appendix). Finally, from your MC results and and plot the entropy as a function
of T.

We compute the thermodynamic property using Monte Carlo Method. We can take
any set of values for a specific temperature instant for the uncertainty quantification.
For the ease of coding, we consider the last set of value for T = 2.00.

Property No of Bin No of points per bin Uncertainty


Energy 100 100 0.005343
Specific Heat 100 100 0.037557
!

Table 3.1 Uncertainty quantification for MC computation

! 15!
Figure 3.2 Comparison of Energy computed by Monte Carlo method with the reference value.
Energy of the system keeps increasing with the increase temperature. After certain temperature, the
system reaches a steady energy value.

Figure 3.3 Comparison of Specific Heat computed by Monte Carlo method with the reference
value. Specific heat takes a sharp change at phase transition.

! 16!
Figure 3.4 Comparison of Specific Heat computed by Monte Carlo method (numerically) with the
reference value. The numerical values are scattered. But with best fitting, it matches with the
reference value.

Figure 3.5 Comparison of Entropy with the reference value. Entropy of the system increases until it
reaches a steady value.

! 17!
4
Use of Monte Carlo Methods to Evaluation
the Thermodynamic Properties of the One-
Dimensional Ising Model
Problem 4.1

Use Monte Carlo methods to evaluate the thermodynamic properties of the one-
dimensional Ising model. Consider c chain of N classical spin one-half particles,
which close on itself, forming a ring. Given ferromagnetic coupling (J > 0) and
nearest-neighbor interactions, the Hamiltonian of this system is
N
H = −J ∑ σ iσ i+1 (4.1)
i=1

with σ = ±1 . One should interpret σ N +1 ≡ σ 1 because the chain is closed.


Find the energy, magnetization, specific heat, and susceptibility of this system
for 0 ≤ kT ≤ 4J using Monte Carlo methods. Do this using the usual metropolis
algorithm to generate spin flips. Let N be around 100 and make about one
million attempted flips at each temperature. Divide the run into ten or so bins
for purposes of determining the uncertainties for the purposes of evaluating
means roughly every N attempted flips (rather than accumulating after each
attempted flip). Pick spins at random.
The exact thermodynamic ( N → ∞ ) functions of this system are not hard to find
analytically. The energy per particle, specific heat, and susceptibility are
J2 e2 J /kT
u = −J tanh ( J / kT ) C= 2
sech 2 ( J / kT ) χ= (4.2)
kT kT
while the magnetization is zero (T ≠ 0 ) . Plot your results, along with the exact
thermodynamic functions, as functions of T.
Should you wish to be more ambitious you may also compute the spin-spin
correlation function. It can also be found analytically and is

! 18!
1 N
g (l ) = ∑ (σ i − σ i
N i=1
)(σ i+1 − σ i+1 ) = tanh l ( J / kT ) (4.3)

where the brackets denote the thermodynamic average of the quantity in


consideration and l ≥ 1. You should notice that this procedure has difficulty
producing decent results at low temperatures because one almost never accepts
spin flips out of the ground state. In this regime, it is more effective to use the
scheme described below. Also, much larger systems (say 10000 spins) must be
simulated. If you wish to be considerably more ambitious you may try to do this
simulation (in addition to the other one, not as an alternative).

We consider a chain of N classical spin one-half particles, which closes on itself,


forming a ring. Given ferromagnetic coupling ( J > 0 ) and nearest-neighbor
interactions. The Hamiltonian of this system:
N
H = −J ∑ σ iσ i+1 (4.4)
i=1

Figure 4.1 Energy for 1D Ising Model

! 19!
Figure 4.2 Magnetization for 1D Ising Model

Figure 4.3 Specific heat for 1D Ising Model

! 20!
Figure 4.4 Susceptibility for 1D Ising Model

Figure 4.5 Uncertainity in computing the thermodynamics quantities for 1D Ising Model

! 21!
Figure 4.6 Spin-Spin Correlation for 1D Ising Model

! 22!
5
Use of Monte Carlo Methods to Evaluation
the Thermodynamic Properties of the Two-
Dimensional Ising Model
Problem 5.1
Use Monte Carlo methods to evaluate the thermodynamic properties of the two-
dimensional Ising model. Consider an Ising model on a two-dimensional square
lattice measuring N × N sites with N = 16. On each site is an object with two
internal states characterized by σ = ±1. There is a nearest-neighbor interaction
between these objects, leading to a Hamiltonian
H = −J ∑ σ iσ j (5.1)
i, j

the sum is over all nearest-neighbor pairs, and periodic boundary conditions are
present.
Find and plot the mean energy, magnetization, specific heat, and susceptibility
of this system for 0 ≤ kT ≤ 4J using Monte Carlo methods with the usual
Metropolis algorithm. Bin the results in order to obtain uncertainties in each
property. Accumulate information for the purpose of evaluating means after
every pass through the lattice; a “pass" is defined as one attempted spin flip per
particle.
For a few temperatures close to (both below and above) the critical temperature,
find and plot the distribution of the magnetization. Is it Gaussian?
Make a serious attempt to write efficient code. Also, look at the difference (in
your results) between picking spins to be flipped at random as opposed to
picking them sequentially.

! 23!
Figure 5.1 Energy for 2D Ising Model

Figure 5.2 Magnetization for 2D Ising Model

! 24!
Figure 5.3 Specific heat for 2D Ising Model

Figure 5.4 Susceptibility for 2D Ising Model

! 25!
Figure 5.5 Uncertainty in computing the thermodynamics quantities for 2D Ising Model

Figure 5.6 Distribution of magnetization around critical temperature. Critical temperature is around
2.20. Around the critical temperature, the distribution is not Gaussian. But away from the critical
temperature, the distribution is Gaussian.
! 26!
6
Kinetic Monte Carlo Method for Langmuir
Adsorption-Desorption Problem
!
Problem 6.1

In this assignment, we will generalize the model for adsorption desorption


kinetics (discussed by Fichthorn and Weinberg, J.Chem.Phys.95, 1090-
1096(1991)) to the case where near-neighbor interactions are included in the
analysis. For 2D square lattice, a given site can be empty or occupied by an atom
0, 1, 2, 3 or 4 neighbors. If a site is empty, an atom can adsorb to the site at a
rA=1s-1. If a site is occupied, the atom at the site can desorb at a rate rDi = rDαi,
where i = 0,1….4 denotes the number of neighbors rD = 2s-1. Here, α = e-ε/kBT,
where ε is the strength of the near neighbor bond.
We consider a 128×128 lattice and assume that initially all sites are empty. For
the cases α = 1, 0.50, 0.25, we will plot the fraction of occupied sites (θ(t) ) as a
function of time until a steady state is reached. At any given instance of time,
there are 6 possible events on the surface: (1) adsorption and (2-6) desorption
from a 0, 1, 2, 3, 4 coordinated sites. We will use periodic boundary conditions
along both the coordinates.

Main Steps for Kinetic Monte Carlo Simulation

1. Categorize and tabulate all the possible types of events and the atoms that can
make each more. Total rate of anything happening on the surface

R= ∑n r i i + Φ
 (6.1)
 i deposition rate
sum over all possible rates

1
If R is the total rate, then on an average one event happens in the time dt = .!
R

! 27!
2. Probability of a process (say i) in that time is

ni ri
Pi = (6.2)
R
Tabulate the probabilities for each event.

3. Choose which process will occur by weighting its relative probability and by
choosing a random number between 0 and 1 and mapping as shown in figure below.

Figure 6.1 Probability map for selection of random map

4. Go to the list it events with chosen rate ri (see step (1)). Chose a candidate
from the list randomly.
5. Execute the chosen event e.g., a jump.
6. Update all the lists to reflect the change in surface configuration.
1
7. Update time by increment dt =
R

8. Go back to (2) and repeat until the required total time has been reached.

! 28!
Langmuir Adsorption-Desorption Problem

Figure 6.2 Langmuir Adsorption-Desorption Problem

! 29!
7
Molecular Dynamics for Simple LJ (Two &
Three Dimensional Particles) Systems
Problem 7.1
The molecular dynamics method consists of solving the equations of motion of a
system. In this exercise you will do that for a very simple system consisting of
just two or three particles in two dimensions with no boundaries on the system.

1. Consider two identical particles, which interact via the Lennard-Jones (6 - 12)
potential. Let these particles be placed initially at positions r1 = 0.60î and r2 = -
60î in natural units. Let their initial velocities be v1 = 0.20ĵ and v2 = -0.20ĵ, also
in natural units; î and ĵ are unit vectors in the x and y directions. Using the
Verlet algorithm with time steps between 0:0001 and 0:010 (in, what else,
natural units), solve for the trajectories of these particles for times on the order
of ten natural units. Plot them three ways: x against t (for both particles), y
against t, and y against x. You should find that the particles are in a bound state,
but you may find the character of their orbits surprising; that is the result of
being raised on gravitational and harmonic forces. Check the energy of the
system occasionally and see to what extent it is conserved. Also, notice that
initially the total momentum of the system is zero and that its center of mass is
at the origin. These properties should remain true as the run progresses. Check
that they do.

2. Now add a third particle, identical to the first two, which is initially located at
r3 = -4î + 0.20 ĵ with initial velocity v3 = 0.50î; it is on a collision course with the
bound pair. The initial states of the first two particles are the same as in part 1.
Using time steps between 0.01 and 0.0001, solve for the trajectories of all three

! 30!
particles for a long enough time that the outcome of the collision is clear. Plot
the trajectories (y against x). Check that the energy and momentum are
conserved to the extent that one expects.
You can use LAMMPS package to do this assignment or write your own
program to do it.

Figure 7.1 x & y vs t ; x vs y. We can notice that the particles are in a bound state and the character
of their orbits surprising; that is the result of being raised on gravitational and harmonic forces.

! 31!
Figure 7.2: Conservation of energy. We can notice that the energy is conserved for the system.

Figure 7.3: Conservation of center of mass and momentum. The C.G. of the system and the velocity
of the C.G. of the system is not changing w.r.t. the time. It means that the center of mass ad
momentum ( = msystem ! vC.G. ) of the system is conserved.

! 32!
Figure 7.4 Trajectories of the system with the inclusion of the third particles.

Figure 7.5 Collision due to the inclusion of the third particles.

! 33!
Figure 7.6 The total energy and momentum of the system is conserved even after the inclusion of
third particles which results in collision.

Problem 7.2

Do a constant energy simulation of a collection of particles with Lennard-Jones


(6-12) interactions truncated at a distance of 2.50σ in a rectangular box (in two
dimensions). Choose the box size so that there are about 100 particles. Let the
particles be on the sites of a triangular lattice initially, and give all particles the
same speed v such that mv2 = 0.60ε. Run simulations with particle densities from
from 0.50σ2 to 0.90σ2 and determine the character (solid, liquid, gas?) of the
equilibrium state in each case. That should be possible by taking a “snapshot” of
the system from time to time, meaning make a plot showing the locations of all
of the particles. Perhaps more useful still would be plots of the particles
trajectories. Monitor the total energy to verify energy conservation. Monitor
also the kinetic and potential energies of each particle to see that nothing
unexpected occurs. Plot the distribution of velocities and obtain the temperature

! 34!
from the slopes. You can use LAMMPS package to do this assignment or write
your own program to do it.

Figure 7.7 The character of the equilibrium state in different cases. For low particle density ρ =
0.50, it behaves like gas. For high-density ρ = 0:90, it is like Solid. In between the state, the system
behaves like Liquid.

! 35!
Figure 7.8 Trajectories of a selected particle for different densities.

Figure 7.9 Energy conservation for the system with different densities.

! 36!
Figure 7.10: Velocity Distribution for the system with different densities.

! 37!
8
Computation of Pressure and Radial
Distribution Function Using LAMMPS
Problem 8.1

Compute the following quantities for a 2D LJ system

1. The pressure, found both from the virial expression. Also try to compute
pressure by considering the force acting across some planes at constant x and/or
y.

2. The pair distribution function g(r), averaged over direction. Use the same
initial conditions as in the previous assignment, i.e., initial particle speed v such
that mv2 = 0.60ε and particle densities from 0.50/σ2 to 0.90/σ2.

Repeat the same calculations for the 3D LJ system. Choose particle densities
from 0.50/σ3 to 0.90/σ3.

Computation of Pressure

• For the pressure computation using command, LAMMPS command compute


pressure is used.

• For the pressure computation by considering the force acting across some
planes at constant x and/or y, a section (here x = xmid) is defined. Using the
LAMMPS command compute group/group, the force acting at the defined
plane is computed. However, since the coordinates of the atoms at the defined
sections are changed at every time step of simulation, the section is redefined
at every time step in order to take care of that.

! 38!
Figure 8.1 Computation of pressure using LAMMPS command and using the concept of force
applied on group.

Radial Distribution Function

Figure 8.2 RDF for 2D LJ System for different densities.

! 39!
Figure 8.3: RDF for 3D LJ System for different densities.

! 40!
9
Computation of Diffusivity and Thermal
Conductivity Using LAMMPS
Problem 9.1

Compute the following quantities for a 2D LJ system:

1. The velocity autocorrelation function.

2. The diffusion coefficient, from the time integral of the velocity autocorrelation
function and also from the Einstein relation.

3. Thermal conductivity from the heat flux auto correlation.

Use the initial conditions as in the previous assignment, i.e., initial particle speed
v such that mv2/2 = 0.60ε and particle densities from 0.50/σ2 to 0.90/σ2.

Particle Diffusivity from Velocity Diffusivity from Thermal


Density Autocorrelation MSD Conductivity
0.50 0.2764945 0.250000 13191.71336
0.70 0.0089060 0.009999 9960.77845
0.90 0.0022585 0.000000 3506.802376
!
Table 9.1 Diffusivity and Thermal Conductivity (LJ Units)

! 41!
Figure 9.1 Velocity Autocorrelation for 2D LJ System

Figure 9.2 Mean Square Displacement

! 42!
10
Indentation Using LAMMPS
Problem 10.1

Perform Indentation using LAMMPS script for 2D LJ system using


Minimization.

Figure 10.1 Snapshots of indentation of 2D LJ system.

! 43!
Appendix A : Matlab Code for Chapter 1

Problem 1.1
!
clear all
clc
format long
N = 4*1000000 ; % sample size
m = 1000 ; % number per bins
n = N/m ; % number of bins
%rand('seed',1234567654)
y = rand([N,1]); %sample
sprintf('Deviation from mean without binning: %f',abs(mean(y)-0.5))
sprintf('Estimation of Error without binning: %f',std(y)/sqrt(N))
sprintf('Analytical estimate of error: %f',sqrt(1/(double(12*N))))
% Compute the means by binning
ybin = zeros(m,n);
ymean = zeros(n,1);
for i = 1:n
ybin(:,i) = y((i-1)*m+1:i*m);
ymean(i) = mean(ybin(:,i));
end
sprintf('Deviation from mean with binning: %f',abs(mean(ymean)-0.5))
sprintf('Estimation of Error with binning: %f',std(ymean)/sqrt(n))
!
Problem 1.2
!
clear all
close all
clc
format long
% --------------- Part # 1 ------------
N = 1*1000000 ; % sample size
m = 10 ; % number per bins
n = N/m ; % number of bins
y = rand([N,1]); %sample
hist(y,10)
! 44!
%---------------- Part #2 --------------
% Fraction of number in each sub interval
% ---------------------------------------
D=10; % 10 bins
xdis = 1/D;
fra_cnt_vec = zeros(D,1);
count = 0;
for i = 1:D;
for j = 1:length(y);
if((y(j)>(i-1)*xdis) && (y(j)<i*xdis));
count = count + 1;
end
end
fra_cnt_vec (i) = count;
count = 0;
end
fra_cnt_vec = (1/N)*fra_cnt_vec ;
% --------------------- Part # 3 --------------------
no_event_bin = N*fra_cnt_vec;
% Compute the mean and variance of the numbers in each bins:
vec_num = [];
vec_mean = [];
vec_var = [];
ind = 0;
for i = 1:D;
for j = 1:length(y);
if((y(j)>(i-1)*xdis) && (y(j)<i*xdis));
ind = ind+1;
vec_num(ind) = y(j);
end
end
% Compute Mean
mean_com = mean(vec_num);
mean_sqr = mean(vec_num.^2);
var_com = mean_sqr - mean_com^2;

! 45!
vec_mean(i) = mean_com;
vec_var(i) = var_com;
vec_num = [];
ind = 0;
end
% ------------------------ Part # 4 --------------------------
% Compute Correlation Function
% -------------------------------------------------------------
% We compute the mean and variance for the whole set of numbers
% -------------------------------------------------------------
mean_globe = mean(y);
meansqr_globe = (mean_globe)^2;
mean_globesqr = mean(y.^2);
cor_vec_0 = mean_globesqr - meansqr_globe ;
cor_vec_0 = cor_vec_0/cor_vec_0;
% Compute coorelation :
% ---------------------
n = 20;
cor_vec = [];
prod = 0;
for n = 1:20;
for j = 1:N;
n_j = n+j;
if (n_j >N);
n_j = mod(n_j,N);
end
prod = prod + y(n_j)*y(j);
end
cor = (1/N)*prod - meansqr_globe ;
cor_vec(n) = cor;
prod = 0;
cor = 0;
end
% -------------------------------------------------

! 46!
Appendix B : Matlab Code for Chapter 2

Problem 2.1
!
clear all
close all
clc
format long
m = 1e5 ; % Number per bins
n = 100 ; % Number of bins
N = m*n; % Sample Size
% ---------------------------------
y = 1 + rand([N,1]); % Generate Sample in between 1 & 2
% Evaluate the integral :
% -----------------------
I = 1./ y;
ymean = zeros(n,1);
for i = 1:n;
ymean(i) = mean(I((i-1)*m+1:i*m));
end
sprintf('Computed Result: %e\n',abs(mean(ymean)))
sprintf('Uncertainty : %e\n',std(ymean)/sqrt(n))
!
Problem 2.2

clear all
close all
clc
format long
m = 1e4 ; % Number per bins
n = 100 ; % Number of bins
N = m*n; % Sample Size
% ---------------------------------
% Evaluate the integral :
% ---------------------------------
dim = 10 ;
sum_ini = 0 ;
! 47!
for j = 1:N;
for i = 1:dim ;
y = rand ;
sin_val = i*y;
sin_val = sum_ini + sin_val ;
sin_val_ini = sin_val;
end
I(j) = sin(pi*sin_val);
sin_val_ini = 0 ;
end
ymean = zeros(n,1);
for i = 1:n;
ymean(i) = mean(I((i-1)*m+1:i*m));
end
sprintf('Computed Answer: %e\n', abs(mean(ymean)))
sprintf('Uncertainty in the result: %e\n',std(ymean)/sqrt(n))
!
Problem 2.3

Importance Sampling

clear all
close all
clc
% ------------------------------------------
format long
N = 2*1e6; % Sample Sizem = 1000 ; % Number per bins
n = N/m ; % Number per bins
% ---------------------------------
y = rand([N,1]); % Generate Sample in between 1 & 2
y = -log(1-y);
% Evaluate the integral :
% -----------------------
deno = 1+2*(sin(y)).^2;
I = 1./ deno.^(0.50);
ymean = zeros(n,1);

! 48!
for i = 1:n;
ymean(i) = mean(I((i-1)*m+1:i*m));
end
sprintf('Computed Value: %e\n',abs(mean(ymean)))
sprintf('Uncertainty : %e\n',std(ymean)/sqrt(n) )

Random Walk Procedure


!
clear all
close all
clc
% ------------------------------------------
format long
N = 1*1e6; % Sample Size
m = 1000 ; % Number per bins
n = N/m ; % Number per bins
% -------------------------------------------------------------------------
a = 10;
x_ini = 0;
for i = 2:N
dx = -a+2*a*rand ;
x_prime = x_ini + dx ;
if (exp(x_prime) > exp(x_ini));
rand_mat(i) = x_prime;
else
prob_new = exp(x_prime)/exp(x_ini);
gen_rand = rand ;
if (gen_rand < prob_new);
rand_mat(i) = x_prime;
else
rand_mat(i) = x_ini;
end
end
x_ini = rand_mat(i);
end
rand_mat(1) = 0;

! 49!
I = rand_mat ;
% Evaluate the integral :
% -----------------------
deno = 1+2*(sin(I)).^2;
I = 1./ deno.^(0.50);
ymean = zeros(n,1);
for i = 1:n;
ymean(i) = mean(I((i-1)*m+1:i*m));
end
sprintf('Computed Value: %e\n',abs(mean(ymean)))
sprintf('Uncertainty : %e\n',std(ymean)/sqrt(n) )

! 50!
Appendix C : Matlab Code and Data files for Chapter 3

Problem 3.1

Matlab Code

clear all
close all
clc
% ---------------------------------------------------
load ref_val.txt ;
temp = ref_val(:,1);
energy = ref_val(:,2);
sp_heat = ref_val(:,3);
% ============= Now generate the data as in the file =========
k = 1; % Boltzman Constant
Delta = 1 ; % Constant Energy
n_states = 100 ; % Number of internal states
% Start Time Increment
count = 0;
for T = 0.02:0.02:2.00;
count = count + 1;
% --------------------------------------
% compute Partition Function
% --------------------------------------
PF_sum = 0;
for n = 1:n_states;
PF = PF_sum + exp(-(n-1)*Delta/(k*T));
PF_sum = PF ;
end
Z(count) = PF ;
% --------------------------------------
% Compute Mean Energy
% --------------------------------------
mean_ener_sum = 0;
for n = 1:n_states;

! 51!
mean_ener = mean_ener_sum + ((n-1)*Delta)*(exp(-(n-1)*Delta/(k*T)))/Z(count);
mean_ener_sum = mean_ener ;
end
E_mean(count) = mean_ener ;
% --------------------------------------
% Compute Mean of Squared Energy
% --------------------------------------
mean_ener_sqr_sum = 0;
for n = 1:n_states;
mean_ener_sqr = mean_ener_sqr_sum + ((n-1)*Delta)^2*(exp(-(n-1)*Delta/(k*T)))/Z(count);
mean_ener_sqr_sum = mean_ener_sqr ;
end
E_sqr_mean(count) = mean_ener_sqr ;
% --------------------------------------
% Time for Specific Heat
% --------------------------------------
spec_heat(count) = (E_sqr_mean(count) - (E_mean(count))^2)/(k*T^2);
% --------------------------------------
end
T = 0.02:0.02:2.00;
plot(T,E_mean,'g','LineWidth',2)
hold on
plot(T,energy,'r+')
hold on
plot(T,spec_heat,'m','LineWidth',2)
hold on
plot(T,sp_heat,'k+')

Problem 3.2

clear all
close all
clc
% ----- Reference Value ------
load ref_val.txt ;

! 52!
temp = ref_val(:,1);
energy = ref_val(:,2);
sp_heat = ref_val(:,3);
% ----- Numerical Value for Different Parameters --
k = 1; % Bolztman Constant
Delta = 1 ; % Constant Energy
n_states = 3 ; % Number of internal states
% -------------------------------------------------
Temp = .02:.02:2;
ini_state = randi([1,3])-1; % initial state
len_temp = length(Temp);
% ---- initializing different vectors --------
ener = zeros(len_temp,1);
Temp=zeros(len_temp,1);
cv = zeros(len_temp,1);
S = zeros(len_temp,1);
count = 0;
delta_T = 0.02; % taken fro the data file sent
for T = .02:delta_T:2;
count = count + 1;
Z = @(n)(exp(-n*Delta/(k*T))); % Exponential of Energy
N = 1e4; % Total number of random number per temperature state
% --- Initialization of vector for each temperature value------
S_vec_t = zeros(N,1);
ener_vec_t = zeros(N,1);
cv_vec_t = zeros(N,1);
ener_sqr_vec_t = zeros(N,1);
Z_vec_t = zeros(N,1);
% ---------------------------------------------------------
for i = 1:N
% ----------------------------------------------------------------
% Stage 1 :: First, pick , with equal probability , either of the
% two states
% ----------------------------------------------------------------
if (rand>.5)

! 53!
new_state = ini_state+1;
if new_state >2
new_state= 0;
end
else
new_state = ini_state-1;
if new_state<0
new_state = 2;
end
end
% --------------------------------------------------------------
% Stage 2 :: Acceptance of the move , accumulation of energy
% ---------------------------------------------------------------
if (ini_state > new_state)
Z_vec_t(i) = Z(new_state);
ini_state=new_state;
else if Z(new_state-ini_state)> rand
Z_vec_t(i) = Z(new_state);
ini_state=new_state;
else
Z_vec_t(i) = Z(ini_state);
end
% ---------------------------------------------------------------
S_vec_t(i) = Z_vec_t(i)*log(Z_vec_t(i));
ener_vec_t(i) = ini_state;
ener_sqr_vec_t(i) = ini_state^2;
end
% ---------------------------------------------------------------
end
PF = sum(Z_vec_t);
ener(count) = sum(ener_vec_t)/PF;
cv(count) = (mean(ener_vec_t.^2)-mean(ener_vec_t)^2)/(k*T^2);
S(count) = -sum(S_vec_t);
Temp(count) = T;
end

! 54!
% Compute Specific Heat Numerically
% -----------------------------------
cv_num = zeros(len_temp,1);
for i = 2:len_temp-1;
cv_num(i) = (ener(i+1)-ener(i-1))/(2*delta_T); %specific heat, numerically
end
% ------------------------------------------------------------------------
plot(Temp,ener,'g*');
hold on
plot(Temp,energy,'r+');
figure
plot(Temp,sp_heat,'r+');
hold on
plot(Temp,cv,'g*');
figure
plot(Temp,cv_num,'m.');
figure
plot(Temp,S,'r -+');

n = 100; % No of bins
m = N/n; % Number per bins
ener_mean = zeros(n,1);
for i = 1:n
ener_mean(i) = mean(ener_vec_t((i-1)*m+1:i*m));
end
sprintf('Binned uncertainty for ener: %f\n',std(ener_mean)/sqrt(n))
n = 20 ; % No of bin
m = len_temp/n ; % Number per bin;
Cvmean = zeros(m,1);
for i = 1:n ;
Cvmean(i) = mean(cv((i-1)*m+1:i*m));
end
sprintf('Binned uncertainty for the Specific Heat: %f\n',std(Cvmean)/sqrt(n))

! 55!
a004.dat Data File

Exact Results
_____________
Temperature Eenergy Specific Heat
--------------------------------------------

0.02000 0.00000 0.00000

0.04000 0.00000 0.00000

0.06000 0.00000 0.00002

0.08000 0.00000 0.00058

0.10000 0.00005 0.00454

0.12000 0.00024 0.01670

0.14000 0.00079 0.04039

0.16000 0.00193 0.07570

0.18000 0.00388 0.12023

0.20000 0.00678 0.17067

0.22000 0.01073 0.22383

0.24000 0.01574 0.27713

0.26000 0.02180 0.32865

0.28000 0.02886 0.37712

0.30000 0.03686 0.42171

0.32000 0.04570 0.46196

0.34000 0.05531 0.49766

0.36000 0.06558 0.52878

0.38000 0.07643 0.55541

0.40000 0.08777 0.57774

0.42000 0.09951 0.59602

0.44000 0.11158 0.61051

0.46000 0.12391 0.62153

! 56!
0.48000 0.13642 0.62938

0.50000 0.14906 0.63438

0.52000 0.16178 0.63683

0.54000 0.17452 0.63703

0.56000 0.18725 0.63524

0.58000 0.19992 0.63171

0.60000 0.21251 0.62670

0.62000 0.22498 0.62041

0.64000 0.23731 0.61303

0.66000 0.24949 0.60474

0.68000 0.26150 0.59571

0.70000 0.27332 0.58606

0.72000 0.28494 0.57593

0.74000 0.29635 0.56542

0.76000 0.30755 0.55463

0.78000 0.31854 0.54364

0.80000 0.32930 0.53253

0.82000 0.33984 0.52134

0.84000 0.35015 0.51015

0.86000 0.36024 0.49899

0.88000 0.37011 0.48791

0.90000 0.37976 0.47692

0.92000 0.38919 0.46608

0.94000 0.39840 0.45538

0.96000 0.40741 0.44487

0.98000 0.41620 0.43453

! 57!
1.00000 0.42479 0.42440

1.02000 0.43318 0.41448

1.04000 0.44137 0.40478

1.06000 0.44937 0.39530

1.08000 0.45718 0.38604

1.10000 0.46481 0.37700

1.12000 0.47227 0.36819

1.14000 0.47954 0.35961

1.16000 0.48665 0.35125

1.18000 0.49359 0.34311

1.20000 0.50038 0.33519

1.22000 0.50700 0.32749

1.24000 0.51348 0.32000

1.26000 0.51981 0.31271

1.28000 0.52599 0.30563

1.30000 0.53203 0.29874

1.32000 0.53794 0.29205

1.34000 0.54371 0.28555

1.36000 0.54936 0.27923

1.38000 0.55489 0.27308

1.40000 0.56029 0.26712

1.42000 0.56557 0.26132

1.44000 0.57074 0.25568

1.46000 0.57580 0.25020

1.48000 0.58075 0.24488

1.50000 0.58560 0.23971

! 58!
1.52000 0.59034 0.23468

1.54000 0.59498 0.22980

1.56000 0.59953 0.22505

1.58000 0.60399 0.22043

1.60000 0.60835 0.21594

1.62000 0.61262 0.21157

1.64000 0.61681 0.20732

1.66000 0.62092 0.20319

1.68000 0.62494 0.19917

1.70000 0.62889 0.19526

1.72000 0.63275 0.19146

1.74000 0.63654 0.18776

1.76000 0.64026 0.18415

1.78000 0.64391 0.18065

1.80000 0.64749 0.17723

1.82000 0.65100 0.17391

1.84000 0.65445 0.17067

1.86000 0.65783 0.16751

1.88000 0.66115 0.16444

1.90000 0.66441 0.16145

1.92000 0.66761 0.15853

1.94000 0.67075 0.15569

1.96000 0.67383 0.15291

1.98000 0.67687 0.15021

2.00000 0.67984 0.14758

! 59!
Appendix D : Matlab Code for Chapter 4

Problem 4.1

clear all
close all
clc
% ------------------------------------------------------------------------
% Input Data
% ------------------------------------------------------------------------
N = 100 ; % No of spins
no_flip = 100000; % No of flip at each temperature
T_start = 0;
T_end = 4 ; % Temperature times the J/k units
dT = 0.020;
J = 1 ; % Strength factor
no_bin = 10 ; % No of bin
no_per_bin = no_flip/no_bin ; % No per bin
% -------------------------------------------------------------------------
% Initialization of the Matrix
% -------------------------------------------------------------------------
spin_vec = zeros(N+1,1);
ener_mean = zeros(no_bin,1);
mag_mean = zeros(no_bin,1);
ener_sqr_mean = zeros(no_bin,1);
mag_sqr_mean = zeros(no_bin,1);
specheat_mean = zeros(no_bin,1);
sus_mean = zeros(no_bin,1);
% ------------------------------------------------------------------------
% make a spin up system
% ---------------------
for i = 1:N+1;
spin_vec(i) = 1 ;
end
% Initialize the energy and the magnetization
% --------------------------------------------------------------

! 60!
ener = 0;
mag = 0;
for i = 1:N;
ener = ener - spin_vec(i)*spin_vec(i+1);
mag = mag + spin_vec(i);
end
% -------------------------------------------------------------
t_range = T_start:dT:T_end ;
count = 0;
for T = t_range ;
count = count + 1;
% For each bin , we perform no_flip number of flips
% --------------------------------------------------------
for b = 1 :no_bin;
ener_sum = 0;
ener_sqr_sum = 0;
mag_sum = 0;
mag_sqr_sum = 0;
for i = 1:no_flip;
pos_flip = floor(rand*N+1);
if (pos_flip > N );
pos_flip = N ;
end
% Compute the change in energy
% ----------------------------
if (pos_flip == 1);
dE = 2*spin_vec(pos_flip)*(spin_vec(N)+spin_vec(pos_flip+1));
else
dE = 2*spin_vec(pos_flip)*(spin_vec(pos_flip-1)+spin_vec(pos_flip+1));
end
% Decide whether the change is possible
% -------------------------------------
if (dE < 0);
spin_vec(pos_flip) = - spin_vec(pos_flip);
ener = ener + dE ;

! 61!
mag = mag + 2*spin_vec(pos_flip);
else
if (rand <= exp(-dE/T));
spin_vec(pos_flip) = - spin_vec(pos_flip);
ener = ener + dE ;
mag = mag + 2*spin_vec(pos_flip);
end
end
% Ends are connected
spin_vec(N+1) = spin_vec(1);
ener_sum = ener_sum + ener;
mag_sum = mag_sum + mag;
ener_sqr_sum = ener_sqr_sum + ener^2;
mag_sqr_sum = mag_sqr_sum + mag^2;
end
ener_mean(b) = ener_sum/no_flip;
mag_mean(b) = mag_sum/no_flip;
ener_sqr_mean(b) = ener_sqr_sum/no_flip;
mag_sqr_mean(b) = mag_sqr_sum/no_flip;
specheat_mean(b) = (ener_sqr_mean(b)-(ener_mean(b))^2)/N/T^2;
sus_mean(b) = (mag_sqr_mean(b)-(mag_mean(b))^2)/N/T;
end
% ------------
Ener(count) = mean(ener_mean)/N ;
Mag(count) = mean(mag_mean)/N ;
Spec_Heat(count)= mean(specheat_mean)/N ;
Sus(count)= mean(sus_mean)/N ;
uncer_Ener(count) = std(ener_mean)/sqrt(no_bin);
uncer_Mag(count) = std(mag_mean)/sqrt(no_bin);
uncer_Spec_Heat(count) = std(specheat_mean)/sqrt(no_bin);
uncer_Sus(count) = std(sus_mean)/sqrt(no_bin);
end
% --------------------- Exact Solution ------------------------
cnt = 0 ;
for i = t_range;

! 62!
cnt = cnt + 1;
exact_ener(cnt) = -tanh(1/i);
exact_mag(cnt) = 0;
exact_sp_heat(cnt) = (1/i^2)*(sech(1/i))^2;
exact_sus(cnt) = exp(2/i)/(J*i);
end
% ----------- Plot the thermodynamic quantities ----------------
% Plot Energy
% -----------
figure
plot(t_range,exact_ener)
hold on
plot(t_range,Ener,'ro')
% Plot Magnetization
% ------------------
figure
plot(t_range,exact_mag)
hold on
plot(t_range,Mag,'ro')
% Plot Specific Heat
% ------------------
figure
plot(t_range,exact_sp_heat)
hold on
plot(t_range,Spec_Heat,'ro')
% Plot Susseptiblity
% ------------------
figure
plot(t_range(100:end),exact_sus(100:end))
hold on
plot(t_range,4*Sus,'ro')
% -------------------- Plot the uncertainities -------------------
% Plot Energy
% -----------
figure

! 63!
subplot(2,2,1)
plot(t_range,uncer_Ener)
xlabel('Temperature')
ylabel('Uncertanity in Energy')
% Plot Magnetization
% ------------------
subplot(2,2,2)
plot(t_range,uncer_Mag)
xlabel('Temperature')
ylabel('Uncertanity in Magnetization')
% Plot Specific Heat
% ------------------
subplot(2,2,3)
plot(t_range,uncer_Spec_Heat)
xlabel('Temperature')
ylabel('Uncertanity in Specific Heat')
% Plot Susseptiblity
% ------------------
subplot(2,2,4)
plot(t_range,uncer_Sus)
xlabel('Temperature')
ylabel('Uncertanity in Susceptibility')
% --------------- Spin-Spin Correlation -----------------
for l = 1:5;
count = 0;
for i = t_range;
count = count + 1;
g_l(count) = (tanh(1/i))^l;
end
plot(t_range,g_l)
hold on
end

! 64!
Appendix E : Matlab Code for Chapter 5

Problem 5.1

clear all
close all
clc
% ------------------------------------------------------------------------
% Input Data
% ------------------------------------------------------------------------
N = 16 ; % No of spins
no_flip = 2^8; % No of flip at each temperature
T_start = 0;
T_end = 4 ; % Temperature times the J/k units
dT = 0.020;
J = 1 ; % Strength factor
no_bin = 100 ; % No of bin
no_per_bin = no_flip/no_bin ; % No per bin
% -------------------------------------------------------------------------
% Initialization of the Matrix
% -------------------------------------------------------------------------
spin_vec = zeros(N+2,N+2);
ener_mean = zeros(no_bin,1);
mag_mean = zeros(no_bin,1);
ener_sqr_mean = zeros(no_bin,1);
mag_sqr_mean = zeros(no_bin,1);
specheat_mean = zeros(no_bin,1);
sus_mean = zeros(no_bin,1);
% ------------------------------------------------------------------------
% make a spin up system
% ---------------------
for i = 1:N+2;
for j = 1:N+2;
spin_vec(i,j) = 1;
end
end

! 65!
% Initialize the energy and the magnetization
% --------------------------------------------------------------
ener = 0;
mag = 0;
for i = 2:N+1;
for j = 2:N+1;
ener = ener - spin_vec(i,j)*(spin_vec(i,j+1) + spin_vec(i+1,j));
mag = mag + spin_vec(i,j);
end
end
% -------------------------------------------------------------
t_range = T_start:dT:T_end ;
count = 0;
for T = t_range ;
count = count + 1;
for b = 1 :no_bin;
ener_sum = 0;
ener_sqr_sum = 0;
mag_sum = 0;
mag_sqr_sum = 0;

for p = 1:round((no_flip/N)^2);
for r = 1:no_flip;
ran_x = floor(rand*N+2);
if (ran_x > N+1);
ran_x = N+1;
end
ran_y = floor(rand*N+2);
if (ran_y > N+1);
ran_y = N+1;
end
%
% ran_x = floor((r-0.00001)/16)+1;
% ran_y = r-(ran_x-1)*16+1;
% ran_x = ran_x +1;

! 66!
% Change in Energy
% ----------------
dE = 2*spin_vec(ran_x,ran_y)*(spin_vec(ran_x,ran_y+1)+spin_vec(ran_x,ran_y-1)+ ...
spin_vec(ran_x+1,ran_y)+spin_vec(ran_x-1,ran_y));
% See if the flip is possible
% ---------------------------
if dE < 0;
spin_vec(ran_x,ran_y) = - spin_vec(ran_x,ran_y);
ener = ener + dE;
mag = mag + 2*spin_vec(ran_x,ran_y);
else
if (rand <= exp(-dE/T));
spin_vec(ran_x,ran_y) = - spin_vec(ran_x,ran_y);
ener = ener + dE;
mag = mag + 2*spin_vec(ran_x,ran_y);
end
end
% Apply periodic boundary condition
% ---------------------------------
for p = 2:N+1;
spin_vec(p,N+2) = spin_vec(p,2);
spin_vec(N+2,p) = spin_vec(2,p);
spin_vec(1,p) = spin_vec(N+1,p);
spin_vec(p,1) = spin_vec(p,N+1);
end
ener_sum = ener_sum + ener;
mag_sum = mag_sum + mag;
ener_sqr_sum = ener_sqr_sum + ener^2;
mag_sqr_sum = mag_sqr_sum + mag^2;
end
end
ener_mean(b) = ener_sum/no_flip;
mag_mean(b) = mag_sum/no_flip;
ener_sqr_mean(b) = ener_sqr_sum/no_flip;
mag_sqr_mean(b) = mag_sqr_sum/no_flip;

! 67!
specheat_mean(b) = (ener_sqr_mean(b)-(ener_mean(b))^2)/N/T^2;
sus_mean(b) = (mag_sqr_mean(b)-(mag_mean(b))^2)/N/T;
end
Ener(count) = mean(ener_mean)/N ;
Mag(count) = mean(mag_mean)/N ;
Spec_Heat(count)= mean(specheat_mean)/N ;
Sus(count)= mean(sus_mean)/N ;
uncer_Ener(count) = std(ener_mean)/sqrt(no_bin);
uncer_Mag(count) = std(mag_mean)/sqrt(no_bin);
uncer_Spec_Heat(count) = std(specheat_mean)/sqrt(no_bin);
uncer_Sus(count) = std(sus_mean)/sqrt(no_bin);
end
% ----------- Plot the thermodynamic quantities ----------------
% Plot Energy
% -----------
figure
plot(t_range,Ener,'ro')
% Plot Magnetization
% ------------------
figure
plot(t_range,Mag,'ro')
% Plot Specific Heat
% ------------------
figure
plot(t_range(20:end),Spec_Heat(20:end),'ro')
% Plot Susseptiblity
% ------------------
figure
plot(t_range(20:end),Sus(20:end),'ro')
% -------------------- Plot the uncertainities -------------------
% Plot Energy
% -----------
figure
subplot(2,2,1)
plot(t_range,uncer_Ener)

! 68!
xlabel('Temperature')
ylabel('Uncertanity in Energy')
% Plot Magnetization
% ------------------
subplot(2,2,2)
plot(t_range,uncer_Mag)
xlabel('Temperature')
ylabel('Uncertanity in Magnetization')
% Plot Specific Heat
% ------------------
subplot(2,2,3)
plot(t_range,uncer_Spec_Heat)
xlabel('Temperature')
ylabel('Uncertanity in Specific Heat')
% Plot Susseptiblity
% ------------------
subplot(2,2,4)
plot(t_range,uncer_Sus)
xlabel('Temperature')
ylabel('Uncertanity in Susceptibility')
%-----------------------------------------
Code for plotting distribution of the magnetization ::
%=====================================================================
====
% Monte Carlo Methods for the evaluation of the thermodynamics properties
% of the two-dimensional Ising model.
% ------------------------------------------------------------------------
clear all
close all
clc
% ------------------------------------------------------------------------
% Input Data
% ------------------------------------------------------------------------
N = 16 ; % No of spins
no_flip = 2^8; % No of flip at each temperature

! 69!
T_start = 0;
T_end = 4 ; % Temperature times the J/k units
dT = 0.020;
J = 1 ; % Strength factor
no_bin = 100 ; % No of bin
no_per_bin = no_flip/no_bin ; % No per bin
% -------------------------------------------------------------------------
% Initialization of the Matrix
% -------------------------------------------------------------------------
spin_vec = zeros(N+2,N+2);
ener_mean = zeros(no_bin,1);
mag_mean = zeros(no_bin,1);
ener_sqr_mean = zeros(no_bin,1);
mag_sqr_mean = zeros(no_bin,1);
specheat_mean = zeros(no_bin,1);
sus_mean = zeros(no_bin,1);
% ------------------------------------------------------------------------
% make a spin up system
% ---------------------
for i = 1:N+2;
for j = 1:N+2;
spin_vec(i,j) = 1;
end
end
% Initialize the energy and the magnetization
% --------------------------------------------------------------
ener = 0;
mag = 0;
for i = 2:N+1;
for j = 2:N+1;
ener = ener - spin_vec(i,j)*(spin_vec(i,j+1) + spin_vec(i+1,j));
mag = mag + spin_vec(i,j);
end
end
% -------------------------------------------------------------

! 70!
t_range = 2;
count = 0 ;
for T = 2:0.50:3.50 ;
count = count + 1;
for b = 1 :no_bin;
ener_sum = 0;
ener_sqr_sum = 0;
mag_sum = 0;
mag_sqr_sum = 0;
for p = 1:round((no_flip/N)^2);
% ------------------------------------------------
for r = 1:no_flip;
ran_x = floor(rand*N+2);
if (ran_x > N+1);
ran_x = N+1;
end
ran_y = floor(rand*N+2);
if (ran_y > N+1);
ran_y = N+1;
end
% Change in Energy
dE = 2*spin_vec(ran_x,ran_y)*(spin_vec(ran_x,ran_y+1)+spin_vec(ran_x,ran_y-1)+ ...
spin_vec(ran_x+1,ran_y)+spin_vec(ran_x-1,ran_y));
% See if the flip is possible
if dE < 0;
spin_vec(ran_x,ran_y) = - spin_vec(ran_x,ran_y);
ener = ener + dE;
mag = mag + 2*spin_vec(ran_x,ran_y);
else
if (rand <= exp(-dE/T));
spin_vec(ran_x,ran_y) = - spin_vec(ran_x,ran_y);
ener = ener + dE;
mag = mag + 2*spin_vec(ran_x,ran_y);
end
end

! 71!
% Apply periodic boundary condition
% ---------------------------------
for p = 2:N+1;
spin_vec(p,N+2) = spin_vec(p,2);
spin_vec(N+2,p) = spin_vec(2,p);
spin_vec(1,p) = spin_vec(N+1,p);
spin_vec(p,1) = spin_vec(p,N+1);
end
ener_sum = ener_sum + ener;
mag_sum = mag_sum + mag;
ener_sqr_sum = ener_sqr_sum + ener^2;
mag_sqr_sum = mag_sqr_sum + mag^2;
end
end
ener_mean(b) = ener_sum/no_flip;
mag_mean(b) = mag_sum/no_flip;
ener_sqr_mean(b) = ener_sqr_sum/no_flip;
mag_sqr_mean(b) = mag_sqr_sum/no_flip;
specheat_mean(b) = (ener_sqr_mean(b)-(ener_mean(b))^2)/N/T^2;
sus_mean(b) = (mag_sqr_mean(b)-(mag_mean(b))^2)/N/T;
end
subplot(2,2,count)
hist(mag_mean)
xlabel(sprintf('T = %0.2f',T));
end

! 72!
Appendix F : Matlab Code for Chapter 6

Problem 6.1
clear all
close all
clc

a = 0.50;
r = zeros([6,1]);
r(1) = 1;

for i =2:6;
r(i) = 2*a^(i-2);
end

t = 0;
% ----------------------------
N = 30000;
ln = 128;
L=zeros(ln+2,ln+2);
P = zeros([6,1]);
Result = zeros([N,2]);

for m = 1:N;

E1 = [0,0];
E2 = [0,0];
E3 = [0,0];
E4 = [0,0];
E5 = [0,0];
E6 = [0,0];
n = zeros([6,1]);
% ---------
for i = 2:ln+1;
for j = 2:ln+1;

! 73!
if L(i,j) == 0;
n(1) = n(1)+1;
E1=[E1;i,j];
else
s = L(i-1,j)+L(i+1,j)+L(i,j+1)+L(i,j-1);

switch s
case 0
n(2) = n(2)+1;
E2 = [E2;i,j];

case 1
n(3) = n(3)+1;
E3 = [E3;i,j];

case 2
n(4) = n(4)+1;
E4 = [E4;i,j];

case 3
n(5) = n(5)+1;
E5 = [E5;i,j];

case 4
n(6) = n(6)+1;
E6 = [E6;i,j];
end
end
end
end
% -------------------------------------------
% Update R
R = 0;
for k = 1:6;

! 74!
R = R+n(k)*r(k);
end
% -------------------------------------------
Result(m,1) = t;
Result(m,2) = (n(2)+n(3)+n(4)+n(5))/ln^2;
% -------------------------------------------
P(1) = n(1)*r(1)/R;
for k = 1:5;
P(k+1) = P(k)+n(k+1)*r(k+1)/R;
end
% -------------------------------------------
% Attemp to Transfer
% ------------------
rd = rand;
% -------------------------------------------
if rd <= P(1);
temp = floor(rand*n(1)+1);
if temp>n(1);
temp = n(1);
end
temp = temp+1;
ei = E1(temp,1);
ej = E1(temp,2);
L(ei,ej) = 1;
if ei == 2;
L(ln+2,ej)=1;
else if ei == ln+1;
L(1,ej)=1;
end
end

if ej == 2;
L(ei,ln+2)=1;
else if ej == ln+1;
L(ei,1)=1;

! 75!
end
end
% ------------------------------------
else if rd <= P(2);
temp = floor(rand*n(2)+1);
if temp>n(2);
temp = n(2);
end
temp = temp+1;
ei = E2(temp,1);
ej = E2(temp,2);
L(ei,ej) = 0;
if ei == 2;
L(ln+2,ej)=1;
else if ei == ln+1;
L(1,ej)=0;
end
end
if ej == 2;
L(ei,ln+2)=0;
else if ej == ln+1;
L(ei,1)=0;
end
end
% ------------------------------------
else if rd <= P(3);
temp = floor(rand*n(3)+1);
if temp>n(3);
temp = n(3);
end
temp = temp+1;
ei = E3(temp,1);
ej = E3(temp,2);
L(ei,ej) = 0;

! 76!
if ei == 2;
L(ln+2,ej)=0;
else if ei == ln+1;
L(1,ej)=0;
end
end
if ej == 2;
L(ei,ln+2)=0;
else if ej == ln+1;
L(ei,1)=0;
end
end

else if rd <= P(4);


temp = floor(rand*n(1)+1);
if temp>n(4);
temp = n(4);
end
temp = temp+1;
ei = E4(temp,1);
ej = E4(temp,2);
L(ei,ej) = 0;
if ei == 2;
L(ln+2,ej)= 0;
else if ei == ln+1;
L(1,ej)=0 ;
end
end
if ej == 2;
L(ei,ln+2)=1;
else if ej == ln+1;
L(ei,1)=0;
end
end

! 77!
else if rd <= P(5);
temp = floor(rand*n(5)+1);
if temp>n(5);
temp = n(5);
end
temp = temp+1;
ei = E5(temp,1);
ej = E5(temp,2);
L(ei,ej) = 0;
if ei == 2;
L(ln+2,ej)=0;
else if ei == ln+1;
L(1,ej)=0;
end
end

if ej == 2;
L(ei,ln+2)=0;
else if ej == ln+1;
L(ei,1)=0;
end
end

else if rd <= P(6);


temp = floor(rand*n(6)+1);
if temp>n(1);
temp = n(1);
end
temp = temp+1;

ei = E6(temp,1);
ej = E6(temp,2);
L(ei,ej) = 0;
if ei == 2;

! 78!
L(ln+2,ej)=1;
else if ei == ln+1;
L(1,ej)=0;
end
end

if ej == 2;
L(ei,ln+2)=0;
else if ej == ln+1;
L(ei,1)=0;
end
end
end
end
end
end
end
end
% --------------------------------------------------------
t = t+1/R;
end
plot(Result(:,1),Result(:,2))

! 79!
Appendix G : Lammps Script for Chapter 7

Problem 6.1
Part 1
units lj
dimension 2
boundary p p p
atom_style atomic
atom_modify map array
# Initialize the system
# ---------------------
read_data data.lj_2
mass 1 1.0
group 1 id 1
group 2 id 2
velocity all create 1.0000 87287 loop geom
velocity 1 set 0 0.200 0 units box
velocity 2 set 0 -0.200 0 units box
# Define the potential
# --------------------
pair_style lj/cut 2.50
pair_coeff * * 1.0 1.0 2.50
pair_modify shift yes
# Information for updating the neighbor list
# ------------------------------------------
neighbor 0.30 bin
neigh_modify delay 0 every 1 check yes
# Specify he type of ensample
# ----------------------------
fix 1 all nve
fix 2 all enforce2d
# Print atomic coordinate every 100 time steps for visualization
# --------------------------------------------------------------
dump vmddump all atom 100 dump.lammpstrj

! 80!
# Thermodynamic information on screen or in log.lammps
# ----------------------------------------------------
timestep 0.0001
thermo 100
thermo_style custom step temp ke pe etotal press
variable mystep equal step*dt
variable mytemp equal temp
variable myke equal ke
variable mype equal pe
variable myetot equal etotal
# Check energy conservation
# --------------------------
fix ener_conser all print 100 "${mystep} ${mytemp} ${myke} ${mype} ${myetot}" file
ener_con.t# Look at the motion of a single atom
# -----------------------------------
group cgroup id 1
variable id_x1 equal x[1]
variable id_y1 equal y[1]
group cgroup id 2
variable id_x2 equal x[2]
variable id_y2 equal y[2]
variable dis_lj2 equal sqrt((v_id_x1-v_id_x2)^2+(v_id_y1-v_id_y2)^2)
variable PosiCG equal xcm(all,x)
variable PosiVel equal vcm(all,x)
fix tracksingleatom cgroup print 10 "${mystep} ${PosiCG} ${PosiVel} ${dis_lj2} ${id_x1}
${id_y# Check that variable takes in result of a compute
# -----------------------------------------------
variable speed atom sqrt(vx*vx+vy*vy+vz*vz)
dump 31 all custom 20000 dumpvel.txt id v_speed
run 100000

Part 2
# Define basic units
# ------------------
units lj

! 81!
dimension 2
boundary p p p
atom_style atomic
atom_modify map array
# Initialize the system
# ---------------------
read_data data.lj_3
mass 1 1.0
group 1 id 1
group 2 id 2
group 3 id 3
velocity all create 1.0000 87287 loop geom
velocity 1 set 0 0.200 0 units box
velocity 2 set 0 -0.200 0 units box
velocity 3 set 0.500 0.000 0 units box
# Define the potential
# --------------------
pair_style lj/cut 2.50
pair_coeff * * 1.0 1.0 2.50
pair_modify shift yes
# Information for updating the neighbor list
# ------------------------------------------
neighbor 0.30 bin
neigh_modify delay 0 every 1 check yes
# Specify he type of ensample
# ----------------------------
fix 1 all nve
fix 2 all enforce2d
# Print atomic coordinate every 100 time steps for visualization
# --------------------------------------------------------------
dump vmddump all atom 100 dump.lammpstrj
# Thermodynamic information on screen or in log.lammps
# ----------------------------------------------------
timestep 0.0001
thermo 100

! 82!
thermo_style custom step temp ke pe etotal press
variable mystep equal step*dt
variable mytemp equal temp
variable myke equal ke
variable mype equal pe
variable myetot equal etotal
# Check energy conservation
# --------------------------
fix ener_conser all print 100 "${mystep} ${mytemp} ${myke} ${mype} ${myetot}" file
ener_con.t# Look at the motion of a single atom
# -----------------------------------
group cgroup id 1
variable id_x1 equal x[1]
variable id_y1 equal y[1]
group cgroup id 2
variable id_x2 equal x[2]
variable id_y2 equal y[2]
group cgroup id 3
variable id_x3 equal x[3]
variable id_y3 equal y[3]
variable PosiCG equal xcm(all,x)
variable PosiVel equal vcm(all,x)
fix tracksingleatom cgroup print 10 "${mystep} ${PosiCG} ${PosiVel} ${id_x1} ${id_y1}
${id_x2}
run 100000

Problem 6.2
units lj
dimension 2
atom_style atomic
atom_modify map array
# Initialize the system
# ---------------------
lattice hex 0.90
region box block 0 8 0 8 -0.1 0.1

! 83!
create_box 1 box
create_atoms 1 box
mass 1 1.0
velocity all create 1.09545 87287 loop geom
# Define the potential
# --------------------
pair_style lj/cut 2.50
pair_coeff * * 1.0 1.0 2.50
pair_modify shift yes
# Information for updating the neighbor list
# ------------------------------------------
neighbor 0.30 bin
neigh_modify delay 0 every 1 check yes
# Specify he type of ensample
# ----------------------------
fix 1 all nve
fix 2 all enforce2d
# Print atomic coordinate every 100 time steps for visualization
# --------------------------------------------------------------
dump vmddump all atom 100 dump.lammpstrj
# Thermodynamic information on screen or in log.lammps
# ----------------------------------------------------
thermo 100
thermo_style custom step temp ke pe etotal press
variable mystep equal step*dt
variable mytemp equal temp
variable myke equal ke
variable mype equal pe
variable myetot equal etotal
# Check energy conservation
# --------------------------
fix ener_conser all print 100 "${mystep} ${mytemp} ${myke} ${mype} ${myetot}" file
ener_con.t# Look at the motion of a single atom
# -----------------------------------
group cgroup id 50

! 84!
variable singlecordx equal x[50]
variable singlecordy equal y[50]
fix tracksingleatom cgroup print 10 "${mystep} ${singlecordx} ${singlecordy}" file singletrack#
Check that variable takes in result of a compute
# -----------------------------------------------
variable speed atom sqrt(vx*vx+vy*vy+vz*vz)
dump 31 all custom 20000 dumpvel.txt id v_speed
run 20000
!

! 85!
Appendix H : Lammps Script and Matlab Code for Chapter 8

Lammps Script
# Define basic units
# ------------------
units lj
dimension 2
atom_style atomic
atom_modify map array
# Initialize the system
# ---------------------
lattice hex 0.60
region box block 0 8 0 8 -0.1 0.1
create_box 1 box
create_atoms 1 box
mass 1 1.0
velocity all create 0.60 87287 loop geom
# Define the potential
# --------------------
pair_style lj/cut 2.50

pair_coeff * * 1.0 1.0 2.50


pair_modify shift yes
# Information for updating the neighbor list
# ------------------------------------------
neighbor 0.30 bin
neigh_modify delay 0 every 1 check yes
# Specify he type of ensample
# ----------------------------
fix 1 all nve
fix 2 all enforce2d
# Print atomic coordinate every 100 time steps for visualization
# --------------------------------------------------------------
dump vmddump all atom 100 dump.lammpstrj

! 86!
# Thermodynamic information on screen or in log.lammps
# ----------------------------------------------------
thermo 100
# -------------------------------------------------------------------------------------------
compute myTemp all temp
region reg_left block INF 4 INF INF INF INF
group gr_left region reg_left
region reg_right block 4 INF INF INF INF INF
group gr_right region reg_right
compute comp_for gr_left group/group gr_right
variable var_for_comp equal -c_comp_for[1]/8
compute peratom all stress/atom
compute p all reduce sum c_peratom[1] c_peratom[2] c_peratom[3]
variable press equal -(c_p[1]+c_p[2]+c_p[3])/(2*vol)
compute 1 all pressure myTemp virial
fix print_val all ave/time 1 1 1 v_var_for_comp file test.txt
thermo_style custom step temp vol press v_press c_1 v_var_for_comp
variable nM loop 2000
label loop
region reg_left delete
region reg_right delete
uncompute comp_for
variable var_for_comp delete
region reg_left block INF 4 INF INF INF INF
group gr_left region reg_left
region reg_right block 4 INF INF INF INF INF
group gr_right region reg_right
compute comp_for gr_left group/group gr_right
variable var_for_comp equal -c_comp_for[1]/8
run 1
next nM
jump lp_hw_8.inp loop

! 87!
Matlab Code

%%%%%%%%%%%%% To read the text file %%%%%%%%%%%%%%%


function tab=readtextfile(filename)
% This function file will read a text file of any format
% =======================================================
% open the file for reading
% -------------------------
ip = fopen(filename,'rt'); % 'rt' means read text
if (ip < 0)
error('could not open file'); % just abort if error
end;
% find length of longest line
% ---------------------------
max=0; % record length of longest string
cnt=0; % record number of strings
s = fgetl(ip); % get a line
while (ischar(s)) % while not end of file
cnt = cnt+1;
if (length(s) > max) % keep record of longest
max = length(s);
end;
s = fgetl(ip); % get next line
end;
% rewind the file to the beginning
% --------------------------------
frewind(ip);
% create an empty matrix of appropriate size
% -------------------------------------------
tab=char(zeros(cnt,max)); % fill with ASCII zeros
% load the strings for real
% -------------------------
cnt=0;
s = fgetl(ip);

! 88!
while (ischar(s))
cnt = cnt+1;
tab(cnt,1:length(s)) = s; % slot into table
s = fgetl(ip);
end;
% close the file and return
% --------------------------
fclose(ip);
return;
% ========= End of the File ===============
%%%%%%%%%%%% Generate RDF Plot %%%%%%%%%%%%%
clear all
close all
clc
% -------------------------------------------------------
op = fopen('2dsys/dump_0p9.txt'); % open the dump file
dump = readtextfile('2dsys/dump_0p9.txt'); % read the dump file
% Extract Data from the dump file
% ===============================
% ----------------
% Number of atoms :
% ----------------
Natom = str2num(dump(4,:));
% --------------------------------------
% Get the total length of the dump file :
% -------------------------------------
L = size(dump);
L = L(1);
% ------------------------------
% Get the total number of snaps :
% ------------------------------
% For any dump file, we will have first 9 colums for information about
% timestep, number of atoms,box size etc
% Total number of snaps available :
Nsnaps_total = L/(Natom +9 ) ;

! 89!
% ------ x,y,z lim -------
xlim = str2num(dump(6,:));
ylim = str2num(dump(7,:));
zlim = str2num(dump(8,:));
Lx = xlim(2) - xlim(1);
Ly = ylim(2) - ylim(1);
Lz = zlim(2) - zlim(1);
%%%%%%%%%%%%%%%%%%%%%%%%%% Load the Coordinate
%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:Nsnaps_total;
coord_all((1+(i-1)*Natom):(i*Natom),:) = (dump((Natom*(i-1)+9*i+1):(Natom+9)*i,:));
end
% - Coordinates above are in string format. Convert it to numerical value -
for i = 1:length(coord_all);
coord(i,:) = str2num(coord_all(i,:));
end
% Input
% -----
% Number of Snaps :
% -----------------
% Maximu available snaps = Nsnaps_total. We can use less than this. For
% accuracy use all snaps available
Nsnaps = Nsnaps_total ;
% Number of histogram bins :
% ---------------------------
% This is for accuracy to plet the histograms.
sizeHistRDF = 200 ;
% -------------------------
% Initialization :
% ----------------
% Sometime if we use until sizeHistRDF, unexpected index error may occure.
% In order to avoid this, we use 2 times of it.
for n = 1:2*sizeHistRDF;
histRDF_total(n) = 0.0;
end

! 90!
% ----------------Main Body to Plot RDF ----------------------------
for i = 1:Nsnaps;
for n = 1:2*sizeHistRDF;
histRDF (n) = 0.0;
end
rangeRDF = 0.50*Lx;
deltaR = rangeRDF / sizeHistRDF ;
for j = 1:Natom;
A(j,1) = Lx*(coord(Natom*(i-1)+j,3));
A(j,2) = Ly*(coord(Natom*(i-1)+j,4));
A(j,3) = Lz*(coord(Natom*(i-1)+j,5));
end
for m = 1: (Natom - 1);
for n = m+1:Natom;
DX = fn_tmpDist(A(n,1),A(m,1),Lx);
DY = fn_tmpDist(A(n,2),A(m,2),Ly);
DZ = fn_tmpDist(A(n,3),A(m,3),Lz);
Dist = sqrt(DX*DX + DY*DY + DZ*DZ);
n = round(Dist/deltaR);
if (n == 0)
n = n+1;
end
histRDF(n) = histRDF(n) + 1;
end
end
normFAC = (Lx*Ly*Lz)/(2*pi*((deltaR)^3)*((Natom)^2));
for n = 1:sizeHistRDF;
histRDF(n) = histRDF(n)*(normFAC/(n-0.50)^2);
histRDF_total(n) = histRDF_total(n) + histRDF(n);
end
end
% -----------------------------------------------------------------------
% Saving the RDF Data for use
% ---------------------------
fid = fopen('RDF_dump_0p9.txt','wt');

! 91!
for n = 1:sizeHistRDF
rb = (n-0.50)*rangeRDF/sizeHistRDF;
fprintf(fid,'%12.8f %12.8f\n',rb, histRDF_total(n)/Nsnaps);
end
% ------------------------------------------------------------------------
% Load the data for RDF Plot
% ----------------------------
load RDF_dump_0p9.txt
RDF_dump_0p9(:,2) = 0.75*ones(1,length(RDF_dump_0p9(:,2)))'+RDF_dump_0p9(:,2);
RDF_dump_0p9 = [RDF_dump_0p9(:,1) RDF_dump_0p9(:,2)];
plot(RDF_dump_0p9(:,1) ,RDF_dump_0p9(:,2),'g')
% --------------------------------------------------------------------------------------------

Matlab file to read text


function tab=readtextfile(filename)
% This function file will read a text file of any format
% =======================================================

% open the file for reading


% -------------------------
ip = fopen(filename,'rt'); % 'rt' means read text

if (ip < 0)

error('could not open file'); % just abort if error

end;

% find length of longest line


% ---------------------------
max=0; % record length of longest string

cnt=0; % record number of strings

s = fgetl(ip); % get a line

while (ischar(s)) % while not end of file

cnt = cnt+1;

if (length(s) > max) % keep record of longest

max = length(s);

end;

! 92!
s = fgetl(ip); % get next line

end;

% rewind the file to the beginning


% --------------------------------
frewind(ip);

% create an empty matrix of appropriate size


% -------------------------------------------

tab=char(zeros(cnt,max)); % fill with ASCII zeros

% load the strings for real


% -------------------------

cnt=0;

s = fgetl(ip);

while (ischar(s))

cnt = cnt+1;

tab(cnt,1:length(s)) = s; % slot into table

s = fgetl(ip);

end;

% close the file and return


% --------------------------
fclose(ip);

return;
% ======== End of the File =============================

! 93!
Appendix I : Lammps Script and Matlab Code for Chapter 9

Lammps Script
# Define basic units
units lj
dimension 2
atom_style atomic
atom_modify map array
# make the box
lattice hex ${den}
region myRegion block -5 5 -5 5 -0.1 0.1
create_box 1 myRegion
#fill box with atoms
create_atoms 1 box
mass * 1.0
# Generate the velocity
velocity all create 0.60 423
# define the potential
pair_style lj/cut 2.5
pair_coeff * * 1.0 1.0 2.5
pair_modify shift yes
#information for updating the neighbor list
neighbor 0.3 bin
neigh_modify delay 0 every 1 check yes
# specify the type of ensemble
fix NVT all nvt temp 0.60 0.60 10 drag 0.2
fix 2 all enforce2d
#run to stablize system
run 2000
unfix NVT
fix NVE all nve
reset_timestep 0
# ----------------------------------------------------------
thermo 100

! 94!
variable myTime equal step*dt
variable myTemp equal temp
compute myKE all ke/atom
compute myPE all pe/atom
compute myStress all stress/atom virial
compute flux all heat/flux myKE myPE myStress
variable Jx equal c_flux[1]/vol
variable Jy equal c_flux[2]/vol
fix JJ all ave/correlate 2 5 100 c_flux[1] c_flux[2] &
type auto file J0Jt.txt ave running
variable k11 equal trap(f_JJ[3])
variable k22 equal trap(f_JJ[4])
compute mymsd all msd com yes
variable compmsd equal c_mymsd[4]
fix prinmsd all print 10 "${myTime} ${compmsd}" file msd_${den}.txt screen no
dump VelDump all custom 10 Vel_${den}.txt id vx vy
thermo_style custom step temp v_Jx v_Jy v_k11 v_k22 ke pe vol
run 1000
variable k equal (v_k11+v_k22)/2.0
variable ndens equal count(all)/vol
print "thermal conductivity :: $k[LJ units] @ 0.60 K, ${ndens}/A^3"

Matlab Code
% -----------------------------------------
% Computation of Velocity auto correlation
% and diffusivity from the plot.
% ----------------------------------------
clear all
close all
clc
% ------------------------------
op = fopen('Vel_0p90.txt'); % open the dump file
dump = readtextfile('Vel_0p90.txt'); % read the dump file
% Extract Data from the dump file
% ===============================

! 95!
% Number of atoms :
% ----------------
Natom = str2num(dump(4,:));
% --------------------------------------
% Get the total length of the dump file :
% -------------------------------------
L = size(dump);
L = L(1);
% ------------------------------
% Get the total number of snaps :
% ------------------------------
% For any dump file, we will have first 9 colums for information about
% timestep, number of atoms,box size etc
% Total number of snaps available :
Nsnaps_total = L/(Natom +9) ;
%%%%%%%%%%%%%%%%%%%%%%%%%% Load the Coordinate
%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:Nsnaps_total;
coord_all((1+(i-1)*Natom):(i*Natom),:) = (dump((Natom*(i-1)+9*i+1):(Natom+9)*i,:));
end
% - Coordinates above are in string format. Convert it to numerical value -
for i = 1:length(coord_all);
coord(i,:) = str2num(coord_all(i,:));
end
% ------------------- Load the Time Vector ---------
time_vec = zeros(1,Nsnaps_total);
dt = 0.005;
for i = 2:Nsnaps_total;
time_vec(i) = str2num(dump(2+(i-1)*(9+Natom),:));
end
time_vec = dt*time_vec;
% ====================================================
% Compute the Velocity Autocorrelation
% ----------------------------------------------------
vel_auto_vec = zeros(1,Nsnaps_total);

! 96!
for i = 1:Nsnaps_total;
sum = 0;
k = (i-1)*Natom;
for j = 1:Natom;
vel_auto = coord(j,2)*coord(j+k,2) + coord(j,3)*coord(j+k,3);
sum = sum + vel_auto;
end
vel_auto_vec(i) = mean(sum)/Natom;
end
% ------------------- Plot ---------------------
plot(time_vec,vel_auto_vec,'LineWidth',2)
hold on
plot(time_vec,zeros(1,Nsnaps_total),'r-')
legend('Density = 0.50',2);
xlabel('Time','LineWidth',2);
ylabel('Velocity Autocorrelation','LineWidth',2);
% ====================================================
% Compute Diffusivity from the Velocity Autocorrelation
% ----------------------------------------------------
diff_coeff = trap_rule(time_vec(end),time_vec(1),Nsnaps_total,vel_auto_vec);
% ====================================================
dim = 2; % Dimension of the system
diff_coeff = diff_coeff/dim;
sprintf('Diffusivity from Velocity Auto Correlation for Density 0.05 (LJ Unit): %e\n', diff_coeff)
% --------------------------------------------------------------------------------------------

! 97!
Appendix J : Lammps Script and Matlab Code for Chapter 10

Lammps Script
dimension 2
boundary p s p
atom_style atomic
neighbor 0.3 bin
neigh_modify delay 5
# create geometry
lattice hex ${den}
region box block 0 40 0 10 -0.25 0.25
create_box 2 box
create_atoms 1 box
mass * 1.0
# LJ potentials
pair_style lj/cut 2.5
pair_coeff * * 1.0 1.0 2.5
# define groups
region 1 block INF INF INF 1.25 INF INF
group lower region 1
group mobile subtract all lower
set group lower type 2
# initial velocities
fix 2 lower setforce 0.0 0.0 0.0
# indenter
fix 5 all enforce2d
# minimize with indenter
thermo 10
dump 1 all atom 10 dump.lammpstrj
#dump 1 all image 25 image.*.jpg type type &
# zoom 1.6 adiam 1.5
#dump_modify 1 pad 4
minimize 1.0e-6 1.0e-6 1000 1000
variable k equal 5000.0/xlat

! 98!
variable k1 equal 1000.0/xlat
variable nM loop 6
label loop
variable ly equal 20.00-0.50*v_nM
fix 4 all indent $k1 sphere 20 v_ly 0 10.0
fix_modify 4 energy yes
minimize 1.0e-6 1.0e-6 1000 1000
next nM
jump in.min loop
% --------------------------------------------------------------------------------------------

! 99!

You might also like