Scientific Computing for Computational
Chemistry: Chem 473
Data Programming - Python as a scientific computing tool
Elliot S. Menkah, Ph.D
National Institute for Mathematical Sciences
Kwame Nkrumah University of Science and Technology
March 13, 2025
Python
Why Python?
▶ It is interpreted and NOT compiled
- E.g. of Compile languages are C/C++, FORTRAN, etc.
▶ It’s a dynamically-typed language.
▶ It can be used interactively.
▶ Syntax is simple, elegant and easily readable.
▶ Free and open source.
▶ It’s powerful due to its ecosystem of libraries.
Python
Why Python?
▶ It is interpreted and NOT compiled
- E.g. of Compile languages are C/C++, FORTRAN, etc.
▶ It’s a dynamically-typed language.
▶ It can be used interactively.
▶ Syntax is simple, elegant and easily readable.
▶ Free and open source.
▶ It’s powerful due to its ecosystem of libraries.
Python
Why Python?
▶ It is interpreted and NOT compiled
- E.g. of Compile languages are C/C++, FORTRAN, etc.
▶ It’s a dynamically-typed language.
▶ It can be used interactively.
▶ Syntax is simple, elegant and easily readable.
▶ Free and open source.
▶ It’s powerful due to its ecosystem of libraries.
Python is versatile.
▶ Download information from a web page.
▶ Manipulate tests to extract and create information.
▶ Animate a world in 3D.
▶ Process huge data sets.
▶ Make publication-quality graphics.
Which version of Python should I use?
▶ Currently two(2) versions: 2.7 and 3.7
▶ Some packages still work only with 2.7
▶ Versions: 2.7 is deprecated
▶ Recommend you use version 3.7
Which version of Python should I use?
▶ Currently two(2) versions: 2.7 and 3.7
▶ Some packages still work only with 2.7
▶ Versions: 2.7 is deprecated
▶ Recommend you use version 3.7
Which version of Python should I use?
▶ Currently two(2) versions: 2.7 and 3.7
▶ Some packages still work only with 2.7
▶ Versions: 2.7 is deprecated
▶ Recommend you use version 3.7
Which version of Python should I use?
▶ Currently two(2) versions: 2.7 and 3.7
▶ Some packages still work only with 2.7
▶ Versions: 2.7 is deprecated
▶ Recommend you use version 3.7
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
ipython Notebook
Why ipython Notebook?
- Gives us a computational notebook with lots of inclusions
▶ Source code in python and other languages
▶ Rich text
▶ Equations written in Latex
▶ Ready output of results
▶ Graphics
▶ Multimedia
Installing Python.
▶ Alternate: package manager ’-apt-get’ on Linux or ’brew’ on
Mac to install python
▶ Anaconda
How do I run python?
#!/bin/(bash or zsh)
$ python
Python 3.6.7 — packaged by conda-forge — (default, Nov 6 2019, 16:03:31)
Type ”help”, ”copyright”, ”credits” or ”license” for more information.
>>>
This is mainly good for running scripts.
#!/bin/bash/zsh
$ ipython
Python 3.6.7 — packaged by conda-forge — (default, Nov 6 2019, 16:03:31)
Type ’copyright’, ’credits’ or ’license’ for more information.
IPython 7.10.2 – An enhanced Interactive Python. Type ’ ?’ for help.
In 1
Anaconda - Conda virtual environment
- exclusive environment
- reinstall anaconda
- package dependencies resolution
Download anaconda via the link: https://www.anaconda.com/distribution/ and
download the installer for your respective OS [Linux , mac , windows]
Create an environment:
1 conda create < envname >
2 Eg .
3 conda create scim561
Connect to environment
1 conda activate scim561
Installing packages into an environment
1 conda install < package >
2 Eg .
3 conda install matplotlib
Deactivate/disconnect from present working environment:
1 conda deactivate
Python Basics
print function, variables, operators
Interpreter - strings and print() function
Print functions and strings:
1 >>> print ( " Hello World " )
2 Hello World
Use double outer quotes (” ”) over single outer quotes (’ ’)
1 >>> print ( ’ We \ ’ re here ’)
2 We ’ re here
to avoid complications.
1 >>> print ( " We ’ re here " )
2 We ’ re here
Interpreter - Variable assignment and Data types
Variables take on the data type of the values being assigned to them.
1 >>> var0 = " hello "
2 >>> var1 = 7
3 >>> var2 = 5.2
4 >>> var3 = True
String Variable:
1 >>> print ( var0 )
2 hello
3 >>> type ( var0 )
4 < type ’ str ’ >
Integer Variable:
1 >>> print ( var1 )
2 7
3 >>> type ( var1 )
4 < type ’ int ’ >
Interpreter - Variable assignment and Data types
Variables take on the data type of the values being assigned to them.
Floating point Variable:
1 >>> print ( var2 )
2 5.2
3 >>> type ( var2 )
4 < type ’ float ’ >
Boolean Variable:
1 >>> print ( var3 )
2 True
3 >>> type ( var3 )
4 < type ’ bool ’ >
Python Operators
Special symbols that carry out arithmetic or logical computation.
Arithmetic Operators Logical Operators
1 + addition 1 = assignment
2 - substraction operator
3 * multiplication 2 == Equal to
4 / division 3 < less than
5 % Modulos 4 > greater
6 // Floor division 5 <= less than or
7 ** Exponential equiv .
8 6 >= greater or equiv .
7 and
8 or
9 not
10
Exercises 1
Given an initial velocity, u, as 10.2 ms −1 , an acceleration, a, of
10.01 ms 2 and a time, t, of 4 seconds, using the python
programming language, write a code to compute the final velocity
of a moving particle with the following formulation
v = u + at.
Exercise 2: The bond dissociation energy
o , is defined as:
The bond dissociation energy, ∆Hrxn
o
∆Hrxn = Σ(Reactants) − Σ(Products) (2)
Given the reaction below, compute the bond enthalpy from the
individual bond enthalpies; H-H (432 kJmol −1 ), Cl-Cl(239
kJmol −1 ), H-Cl(427 kJmol −1 );
1 1
H2 + Cl2 → HCl (3)
2 2
data storage, loops, len and range, if statements
Interpreter - List, Tuples and Dictionaries
1 >>> x = [ " Hey " , " you " , 5 , 8.7]
2 >>> y = ( " hello " , " hi " , " you " )
3 >>> w = { " foo " : 1.0 , " bar " : 2.0 }
4 >>> print ( type ( x ) )
5 >>> < class ’ list ’ >
6 >>> print ( type ( y ) )
7 >>> < class ’ tuple ’ >
8 >>> print ( type ( w ) )
9 >>> < class ’ dict ’ >
Empty list:
1 >>> x = []
2 >>> x
3 [ ]
Interpreter - List, Tuples and Dictionaries
Indexing and memory location:
Memory locations for storing data in list and tuples are indexed so that one
could access data stored in a specific memory locations.
NB: By default, index locations begin from zero (0).
1 >>> z = [2 , 3 , 4 , 5]
2 >>> num0 = z [0]
3 >>> print ( num0 )
4 2
Interpreter - List, Tuples and Loops
Loops, List and range:
1 >>> for i in z : 1 2
2 ... print ( i ) 2 3
3 ... 3 4
4 5
range & len intrinsic functions
1 >>> range (4) 0 = Starting index
2 range (0 ,4) 4 = Total no. of numbers
3 >>> len ( z ) 4 = Number of elements in list z.
4 4
Interpreter - List, Tuples and Loops
range and len can be combined and used in loops:
1 >>> for i in range ( len ( z ) ) :
1 0
2 ... print ( i )
2 1
3 ...
3 2
4 3
len gives length of list z, that is, 4.
range gives 4 integers used as indexes starting from index 0.
Interpreter - While loops and Boolean
while loops, if statements and boolean
1 >>> a = True :
1 1
2 >>> print ( a )
2 2
3 True
3 3
4 >>> res = 0
4 4
5 >>> while ( a ) :
5 ...
6 ... res += 1
7 ... print ( res )
8 ... if ( res >= 10) :
9 ... a = False
boolean a changes to False and it is used to terminate loop in the
condition test section
modules
Modules - import, help, dir
There are lots of libraries in Python that can be imported to use rather than
having to build your own. This makes life much easier.
E.g. math
1 >>> import math
Docs of modules can be viewed with the help and dir methods.
1 >>> help ( < module >)
2 >>> help ( math )
3 ...
4 ...
5 ...
6 >>> dir ( math ) or >>> print ( dir ( math ) )
help gives a comprehensive documentation of the module.
dir gives you the symbols contained in the method concerned.
Modules - import, help, dir
1 >>> help ( math . log )
2 ...
3 ...
4 ...
import math place the math class in current environment.
1 >>> math . log (10)
2 2.3025
3 >>> math . cos (2 * math . pi )
4 1.0
Modules - More on import
Partial or selective importation of modules.
In the event of wanting to import only a few symbols into your namespace, the
from statement is made use of.
1 >>> from math import < symbol or method >
2 >>> from math import cos
3 >>> cos (90)
4 -0.4480736161291701
Multiple methods can be imported
1 >>> from math import cos , pi
2 >>> cos (2 * pi )
3 1.0
Plotting - Matplotlib
Matplotlib
1 import matplotlib . pyplot as plt
2
3 plt . plot ( X_data , Y_data )
4 plt . title ( " Title of plot " )
5 plt . xlabel ( " X Axis Lable " )
6 plt . ylabel ( " Y axis Label " )
7
8 plt . savefig ( " NameOfFile . png " )
9
10
Listing: Plottin with Matplotlib
functions
Functions
Functions in Python are defined by the keyword def
1 >>> def func ( x ) :
2 ... res = x + 1
3 ... return res
4 ...
5 >>> d = func (4)
6 >>> d
7 5
Python scripts
Script Terminal
1 # ! / usr / bin / python 1 python3 hello . py
2
3 print ( " Hello World " )
Exercises 2
Convert your code from Exercise 1 into a function (that returns a
value), where the initial condition, u, and the time, t, are
arguments.
Exercises 3 - Algorithm Development
Exercise A: Multiples of 3 & 5
If we list all the natural numbers below 10 that are multiples of 3
or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Implement an algorithm, with Python, to find the sum of all the
multiples of 3 or 5 below 1000.
Exercise B: Fibonacci sequence
Each new term of the Fibonacci sequence is generated by adding
the previous two terms. By starting with 1 and 2, the first 10
terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms of the Fibonacci sequence whose values
do not exceed four million, find the sum of the even-valued terms.
arrays and multidimensional vectors
Handling Arrays & Multidimensional Vectors
Vector Operation
N
X
⃗a · ⃗b = ai b i
i=0
20 15
= −3 −2.249
5 1
20(15) + 20(−2.249) + 20(1)
= −3(15) + −3(−2.249) + −3(1)
5(15) + 5(−2.249) + 5(1)
300 + 44.98 + 20
= −45 + 6.747 − 3
75 + −11.245 + 5
364.98
= −41.253
68.755
Handling Arrays & Multidimensional Vectors
Multidimensional Arrays
20 15 10 45 20 15 10 45
−3 −2.249 7 1.751 = −3 −2.249 7 1.751
5 1 3 9 5 1 3 9
file I/O, exceptions and assertions
File I/O
keyword: open
1 >>> fh = open ( " demofile . txt " , " a " )
2 >>> fh . write ( " My data file \ n " )
3 >>> fh . write ( " Results : % d " , res )
4 >>> fh . close
Exceptions and Assertions
This is a way to handle expected and unexpected errors.
1. Exceptions Handling
2. Assertion
1 try :
2 # Runs First
3 < code >
4 except :
5 # Runs if exceptions occurs in try block
6 < code >
7 else :
8 # Executes if try block succeeds .
9 < code >
10 finally :
11 # This code always runs executes .
12 < code >
Exceptions and Assertions
Exception Example
1 def read_file ( path ) :
2 """ Return the content of a file at path """
3 try :
4 fh = open ( path , mode = " rb " )
5 data = f . read ()
6 return data
7 except Fil eNotFoundError as err :
8 raise
9 else :
10 fh . close
11 finally :
12 print ( " Leaving file read routine " )
Python Basics - End
End of Basics.
Questions ?
Review
Numerical and Scientific Python
Numerical and Scientific Python
Numpy and Scipy libraries
Numerical Python - NumPy
Arrays could be made from:
1. Python list or tuples
2. Using functions that are dedicated to generating numpy
arrays, such as arange, linspace, etc.
3. Reading data from files
1 from numpy import as np
2 v = array ([1 ,2 ,3 ,4])
3 -----
4 [1 ,2 ,3 ,4]
1 M = np . array ([[1 , 2] , [3 , 4]])
2 -----
3 array ([[1 , 2] ,
4 [3 , 4]])
Exercises 4
Using the python programming language, write a code that
implements the solution or finds the roots of the non-linear
equation:
3x 2 + 2x + 1 = 0
using the
1. Bisection Method
2. Newton-Raphson’s Method
3. Secant Method
as separate functions.
Classes
Classes in Python are defined by the keyword class
1 >>> class myfunctions :
2 ...
3 ... def add ( x ) :
4 ... res = x + 2
5 ... return res
6 >>>
7 >>> yy = myfunctions . add (7)
8 >>> yy
9 9
10
End of talk
Thank you