MM220: Computational Lab
Amrita Bhattacharya
April 11, 2019
1 Introduction to python -III: plotting, integration and optimzation
1.1 Locating, adding, and importing libraries
Python has strong in built libraries for numerical and scientific operations such as Numpy, Scipy,
Sympy etc. Locate your libraries and add path of the libraries in your preamble (if required).
Listing 1: locate
locate numpy
locate scipy
Add the following in your preamble (if required), depending upon your search result to the path of
the libraries;
Listing 2: path
#!/usr/bin/python
#!/usr/share/pyshared/
#!/usr/share/pyshared/scipy
Import the libraries, depending on their need;
Listing 3: Import
import matplotlib.pyplot as plt;
import numpy as np;
import scipy.optimize as opt;
1
1.2 Integration
Listing 4: integration
import scipy
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from numpy import array
from scipy.integrate import quad
import sympy
###### Define the function ########
def func(x):
return 4*x**2 +2
###### Definite integration #######
def int_func(a, b):
I= quad(func, a , b)
return I[0]
print int_func(0, 2)
###### Symbolic integration #######
def int(x):
x = sympy.symbols('x')
val =sympy.integrate(func(x), x)
return val
######## Plotting done here ########
x = sympy.symbols('x')
intx=[]
for i in np.linspace(-3,3):
intx.append(int(x).evalf(subs={x: i}))
x = np.linspace(-3,3)
plt.plot(x,func(x))
plt.plot(x,intx)
plt.xlabel("x")
plt.ylabel("y")
plt.legend(('f(x)', 'int(f(x))' ))
plt.savefig('int.eps')
plt.show()
The output of the given program should be as follows;
2
40
20
y
0
−20
f(x)
−40 int(f(x))
−3 −2 −1 0 1 2 3
x
Figure 1: Plot of integration of a function.
1.3 Polynomial fitting
Listing 5: polyfit
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
v = np.array([13.72, 14.83, 16.0, 17.23, 18.52])
e = np.array([-56.29, -56.41, -56.46, -56.46, -56.42])
print v.shape, e.shape
### fit a parabola to the data
# y = cx^2 + bx + a
a = np.polyfit(v,e,2)
print a
plt.plot(v,e)
#make a vector to evaluate fits on with a lot of points so it looks smooth
vfit = np.linspace(min(v),max(v),100)
plt.plot(vfit, (a[0]*vfit**2 + a[1]*vfit + a[2]))
plt.legend(('original', 'parabolic fit'))
plt.xlabel("Volume ($\AA^3$)")
plt.ylabel("Energy (eV)")
plt.savefig('eos.eps')
plt.show()
3
original
−56.300 parabolic fit
−56.325
−56.350
Energy (eV) −56.375
−56.400
−56.425
−56.450
−56.475
14 15 16 17 18
Volume (Å 3)
Figure 2: Plot showing the total energy plotted as a function of volume.
4
1.4 Optimization
Listing 6: leastsquare
import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
def gen_data(t, a, b, c, noise=0, n_outliers=0, random_state=0):
y = a + b * np.exp(t * c)
rnd = np.random.RandomState(random_state)
error = noise * rnd.randn(t.size)
outliers = rnd.randint(0, t.size, n_outliers)
error[outliers] *= 10
return y + error
a = 0.5
b = 2.0
c = -1
t_min = 0
t_max = 10
n_points = 15
t_train = np.linspace(t_min, t_max, n_points)
y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)
print t_train, y_train
def fun(x, t, y):
return x[0] + x[1] * np.exp(x[2] * t) - y
x0 = np.array([1.0, 2.1, 0.0])
res_lsq = leastsq(fun, x0, args=(t_train, y_train))
print res_lsq, res_lsq[0][0], res_lsq[0][1]
plt.plot(t_train, y_train, '.')
plt.plot(t_train, res_lsq[0][0] + res_lsq[0][1] * np.exp(res_lsq[0][2] * t_train))
plt.xlabel("x")
plt.ylabel("y")
plt.savefig('opt.eps')
plt.show()
5
3.0
2.5
2.0
y 1.5
1.0
0.5
0 2 4 6 8 10
x
Figure 3: Plot showing the optimized fit to data points.
1.5 Reading writing file
Given a file "lat.dat". You can read, modify, and save it as "modlat.dat" using the following program.
6
Listing 7: R/W
import matplotlib.pyplot as plt;
import numpy as np;
########## Reading a file ############
file= open("lat.dat", "r")
mod_file = open("modlat.dat", "w")
lat=[]
while True:
line= file.readline()
if line:
lat.append(map(float, line.split()[0:]))
if not line:
break
file.close()
print len(lat), lat[0][0]
########### Writing the file #############
for i in range(len(lat)):
mod_file.write('%6.6f %6.6f \n' %(lat[i][0], lat[i][1] ))
mod_file.close()
############ Direct reading #################
x, y = np.loadtxt('lat.dat', delimiter=None, unpack=True)
############ Plotting ####################
plt.xlabel("lattice_parameter (A)")
plt.ylabel("Energy (eV)")
plt.plot(x,y, label='Loaded from file!')
plt.savefig('latenergy.eps')
plt.show()
−3.62202e5
−0.38
−0.40
Energy (eV)
−0.42
−0.44
−0.46
10.10 10.12 10.14 10.16 10.18
lattice_parameter (A)
Figure 4: Plot showing the total energy plotted as a function of volume.
7
2 Assignments
1. f (x) = xex . Use symbolic python to write a program that integrates and plots f (x) and
R
f (x)dx
in the same graph for a range of 0 < x < 3.
2. The Birch Murnaghan equation of state (BM EOS) is a relationship between the volume and
energy of the solid;
" #3 #2 "
2 " 2 2 #
9V0 B0 V0 3 0 V0 3 V0 3
E (V ) = E0 + − 1 B0 + −1 6−4 (1)
16 V V V
The internal energy (E) is a function of the volume (V ), where the parameters at the equilibrium
i.e. the energy E0 , volume V0 , bulk modulus B0 and it’s derivative B00 can be obtained from the
fit of E and V .
In the following, we will use BM EOS fit to calculate the bulk modulus B0 and it’s derivative B00
of a solid phase of Si clathrate.
(a) The file "lat.dat" gives the energy of a cubic bulk solid phase (Si clathrate) as a function of
lattice parameter. Modify the file to create a new file called "latmod.dat", so that it gives energy
as a function of volume of the solid. This relationship between volume and energy of the soild
can be used for fitting the BM EOS.
(b) In order to fit the data to the BM EOS, you will have to make initial guesses of the parameters
E0 , V0 , B0 and B00 . For this perform a polynomial fitting to the clathrate EOS and identify the
coefficients a, b and c. So that the energy (E) is expanded as a function of volume (V ) using the
coefficients a, b and c and the parameters can be identified as follows;
Listing 8: Init
E = a V2 + b V + c
dE/dV = 2 a V + b
d2 E/dV2 = 2a
V0 = -b/2a (∵ dE/dV =0 at equillibrium)
E0 = a V0 2 +b V0 + c
B0 = V0 d2 E/dV2 = 2a V0
B'0 = 4 (∵ It is a small number usually)
Plot E as obtained in above with your original E-V data.
(c) Using the initial parameters as obtained from (b) set up a function that optimizes the energy
using the BM EOS taking the initial parameters and volume as argument. Print the optimized
equilibrium parameters i.e. the energy E0 , volume V0 , bulk modulus B0 and its derivative B’0 .