None
The purpose of this Jupyter Notebook is to get you started using Python and Jupyter Notebooks for routine chemical engineering calculations. This introduction assumes this is your first exposure to Python or Jupyter notebooks.
Jupyter notebooks are documents that can be viewed and executed inside any modern web browser. Since you're reading this notebook, you already know how to view a Jupyter notebook. The next step is to learn how to execute computations that may be embedded in a Jupyter notebook.
To execute Python code in a notebook you will need access to a Python kernal. A kernal is simply a program that runs in the background, maintains workspace memory for variables and functions, and executes Python code. The kernal can be located on the same laptop as your web browser or located in an on-line cloud service.
Important Note Regarding Versions There are two versions of Python in widespread use. Version 2.7 released in 2010, which was the last release of the 2.x series. Version 3.5 is the most recent release of the 3.x series which represents the future direction of language. It has taken years for the major scientific libraries to complete the transition from 2.x to 3.x, but it is now safe to recommend Python 3.x for widespread use. So for this course be sure to use latest verstion, currently 3.6, of the Python language.
The easiest way to use Jupyter notebooks is to sign up for a free or paid account on a cloud-based service such as Wakari.io or SageMathCloud. You will need continuous internet connectivity to access your work, but the advantages are there is no software to install or maintain. All you need is a modern web browser on your laptop, Chromebook, tablet or other device. Note that the free services are generally heavily oversubscribed, so you should consider a paid account to assure access during prime hours.
There are also demonstration sites in the cloud, such as tmpnb.org. These start an interactive session where you can upload an existing notebook or create a new one from scratch. Though convenient, these sites are intended mainly for demonstration and generally quite overloaded. More significantly, there is no way to retain your work between sessions, and some python functionality is removed for security reasons.
For regular off-line use you should consider installing a Jupyter Notebook/Python environment directly on your laptop. This will provide you with reliable off-line access to a computational environment. This will also allow you to install additional code libraries to meet particular needs.
Choosing this option will require an initial software installation and routine updates. For this course the recommended package is Anaconda available from Continuum Analytics. Downloading and installing the software is well documented and easy to follow. Allow about 10-30 minutes for the installation depending on your connection speed.
After installing be sure to check for updates before proceeding further. With the Anaconda package this is done by executing the following two commands in a terminal window:
> conda update conda
> conda update anaconda
Anaconda includes an 'Anaconda Navigator' application that simplifies startup of the notebook environment and manage the update process.
If you are using a cloud-based service a Jupyter session will be started when you log on.
If you have installed a Jupyter/Python distribution on your laptop then you can open a Jupyter session in one of two different ways:
open a terminal window on your laptop and execute the following statement at the command line:
> jupyter notebook
Either way, once you have opened a session you should see a browser window like this:
At this point the browser displays a list of directories and files. You can navigate amoung the directories in the usual way by clicking on directory names or on the 'breadcrumbs' located just about the listing.
Jupyter notebooks are simply files in a directory with a .ipynb
suffix. They can be stored in any directory including Dropbox or Google Drive. Upload and create new Jupyter notebooks in the displayed directory using the appropriate buttons. Use the checkboxes to select items for other actions, such as to duplicate, to rename, or to delete notebooks and directories.
New Notebook
button, or An IPython notebook consists of cells that hold headings, text, or python code. The user interface is relatively self-explanatory. Take a few minutes now to open, rename, and save a new notebook.
Here's a quick video overview of Jupyter notebooks.
from IPython.display import YouTubeVideo
YouTubeVideo("HW29067qVWk",560,315,rel=0)
Python is an elegant and modern language for programming and problem solving that has found increasing use by engineers and scientists. In the next few cells we'll demonstrate some basic Python functionality.
Basic arithmetic operations are built into the Python langauge. Here are some examples. In particular, note that exponentiation is done with the ** operator.
a = 12
b = 2
print(a + b)
print(a**b)
print(a/b)
14 144 6.0
The Python language has only very basic operations. Most math functions are in various math libraries. The numpy
library is convenient library. This next cell shows how to import numpy
with the prefix np
, then use it to call a common mathematical functions.
import numpy as np
# mathematical constants
print(np.pi)
print(np.e)
# trignometric functions
angle = np.pi/4
print(np.sin(angle))
print(np.cos(angle))
print(np.tan(angle))
3.141592653589793 2.718281828459045 0.707106781187 0.707106781187 1.0
Lists are a versatile way of organizing your data in Python. Here are some examples, more can be found on this Khan Academy video.
xList = [1, 2, 3, 4]
xList
[1, 2, 3, 4]
Concatentation is the operation of joining one list to another.
# Concatenation
x = [1, 2, 3, 4];
y = [5, 6, 7, 8];
x + y
[1, 2, 3, 4, 5, 6, 7, 8]
Sum a list of numbers
np.sum(x)
10
An element-by-element operation between two lists may be performed with
print(np.add(x,y))
print(np.dot(x,y))
[ 6 8 10 12] 70
A for loop is a means for iterating over the elements of a list. The colon marks the start of code that will be executed for each element of a list. Indenting has meaning in Python. In this case, everything in the indented block will be executed on each iteration of the for loop. This example also demonstrates string formatting.
for x in xList:
print("sin({0}) = {1:8.5f}".format(x,np.sin(x)))
sin(1) = 0.84147 sin(2) = 0.90930 sin(3) = 0.14112 sin(4) = -0.75680
Dictionaries are useful for storing and retrieving data as key-value pairs. For example, here is a short dictionary of molar masses. The keys are molecular formulas, and the values are the corresponding molar masses.
mw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01}
mw
{'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0}
We can a value to an existing dictionary.
mw['C8H18'] = 114.23
mw
{'C8H18': 114.23, 'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0}
We can retrieve a value from a dictionary.
mw['CH4']
16.04
A for loop is a useful means of interating over all key-value pairs of a dictionary.
for species in mw.keys():
print("The molar mass of {:<s} is {:<7.2f}".format(species, mw[species]))
The molar mass of H2O is 18.02 The molar mass of CH4 is 16.04 The molar mass of C8H18 is 114.23 The molar mass of O2 is 32.00 The molar mass of CO2 is 44.01
Dictionaries can be sorted by key or by value
for species in sorted(mw):
print(" {:<8s} {:>7.2f}".format(species, mw[species]))
C8H18 114.23 CH4 16.04 CO2 44.01 H2O 18.02 O2 32.00
for species in sorted(mw, key = mw.get):
print(" {:<8s} {:>7.2f}".format(species, mw[species]))
CH4 16.04 H2O 18.02 O2 32.00 CO2 44.01 C8H18 114.23
Importing the matplotlib.pyplot
library gives IPython notebooks plotting functionality very similar to Matlab's. Here are some examples using functions from the
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10)
y = np.sin(x)
z = np.cos(x)
plt.plot(x,y,'b',x,z,'r')
plt.xlabel('Radians');
plt.ylabel('Value');
plt.title('Plotting Demonstration')
plt.legend(['Sin','Cos'])
plt.grid()
plt.plot(y,z)
plt.axis('equal')
(-1.09972447591003, 1.0979832896606587, -1.0992804688576738, 1.0999657366122702)
plt.subplot(2,1,1)
plt.plot(x,y)
plt.title('Sin(x)')
plt.subplot(2,1,2)
plt.plot(x,z)
plt.title('Cos(x)')
<matplotlib.text.Text at 0x112e79390>
import sympy as sym
sym.var('P V n R T');
# Gas constant
R = 8.314 # J/K/gmol
R = R * 1000 # J/K/kgmol
# Moles of air
mAir = 1 # kg
mwAir = 28.97 # kg/kg-mol
n = mAir/mwAir # kg-mol
# Temperature
T = 298
# Equation
eqn = sym.Eq(P*V,n*R*T)
# Solve for P
f = sym.solve(eqn,P)
print(f[0])
# Use the sympy plot function to plot
sym.plot(f[0],(V,1,10),xlabel='Volume m**3',ylabel='Pressure Pa')
85521.9882637211/V
<sympy.plotting.plot.Plot at 0x11439fda0>
Python offers a full range of programming language features, and there is a seemingly endless range of packages for scientific and engineering computations. Here are some suggestions on places you can go for more information on programming for engineering applications in Python.
This excellent introduction to python is aimed at undergraduates in science with no programming experience. It is free and available at the following link.
The following text is licensed by the Hesburgh Library for use by Notre Dame students and faculty only. Please refer to the library's acceptable use policy. Others can find it at Springer or Amazon. Resources for this book are available on github.
pycse is a package of python functions, examples, and document prepared by John Kitchin at Carnegie Mellon University. It is a recommended for its coverage of topics relevant to chemical engineers, including a chapter on typical chemical engineering computations.
Raw
button to download the .pdf
file.