J.C. Kantor ([email protected])

Jupyter notebooks are documents that can be viewed and executed using 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 code in a notebook you will need access to a computation. You can do this through an on-line cloud-based service, or by installing a suitable computational environment on your laptop.

The easiest approach is to sign up for a free 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 nothing to install, no software to maintain. All you need is a modern web browser on your laptop, Chromebook, tablet or other device.

There are also demonstration sites in the cloud, such as tmpnb.org. These will start up a interactive session where you can upload an existing notebook, or create a new one from scratch. While convenient, these sites are intended mainly for demonstration. There is no way to retain your work between sessions, and not all functionality is available.

Alternatively, to gain off-line access you can install a Jupyter Notebook/Python environment directly on your laptop. This will provide you with reliable off-line access to a computational environment to which you can add additional functionaility to meet your particular needs. This option does require an initial installation and routine updates.

There are at least two excellent and free packages available for free download:

- Anaconda available from Continuum Analytics.
- Enthought Canopy available from Enthought, Inc.

There are differences between these packages, particularly in the methods used to download and maintain additional Python libraries. In both cases the process for downloading and installing the software are 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 simplify 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:

- Use the Anaconda Navigator App, or
open a terminal window on your laptop, then execute the following statement at the command line:

`> ipython 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.

To start a notebook session, open a terminal window and navigate to the directory where you will be keeping your notebooks. Then execute the following statement at the command line:

```
> ipython notebook
```

The terminal window will show information indicating start up of an ipython session, then browser window will open listing notebooks in your current directory. At this point your options are

- select one of your existing notebooks to work on,
- start a new notebook by clicking on the
`New Notebook`

button, or - import a notebook from another directory by dragging it onto the list of notebooks.

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 overview of IPython notebooks prepared by the team that created the software.

In [1]:

```
from IPython.display import YouTubeVideo
YouTubeVideo("H6dLGQw9yFQ",560,315,rel=0)
```

Out[1]:

In [ ]:

```
```

Basic arithmetic functions

In [2]:

```
a = 12
b = 2
print "a + b = ", a + b
print "a**b = ", a**b
print "a/b = ", a/b
```

`numpy`

library. This next cell shows how to import `numpy`

with the prefix `np`

, then use it to call a common function

In [3]:

```
import numpy as np
np.sin(2*np.pi)
```

Out[3]:

In [4]:

```
xList = [1, 2, 3, 4]
print xList
```

Concatentation is the operation of joining one list to another.

In [5]:

```
# Concatenation
x = [1, 2, 3, 4];
y = [5, 6, 7, 8];
x + y
```

Out[5]:

`sum`

function from `numpy`

, or using python's build-in `reduce`

function. The advantage of `reduce`

is that it can extend any pairwise operation to work on a list.

In [6]:

```
# Two ways to sum a list of numbers
print np.sum(x)
print reduce(np.add,x)
```

`map`

function.

In [7]:

```
# Two ways to add a two lists of numbers
print np.add(x,y)
print map(np.add,x,y)
```

In [8]:

```
for x in xList:
print "x =", x, " sin(x) = ", np.sin(x)
```

In [9]:

```
mw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01}
print mw
```

We can a value to an existing dictionary.

In [10]:

```
mw['C8H18'] = 114.23
print mw
```

We can retrieve a value from a dictionary.

In [11]:

```
mw['CH4']
```

Out[11]:

A for loop is a useful means of interating over all key-value pairs of a dictionary.

In [12]:

```
for species in mw.keys():
print "The molar mass of {:<s} is {:<7.2f}".format(species, mw[species])
```

Dictionaries can be sorted by key or by value

In [13]:

```
for species in sorted(mw):
print " {:<8s} {:>7.2f}".format(species, mw[species])
```

In [14]:

```
for species in sorted(mw, key = mw.get):
print " {:<8s} {:>7.2f}".format(species, mw[species])
```

`matplotlib.pyplot`

library gives IPython notebooks plotting functionality very similar to Matlab's. Here are some examples using functions from the

In [15]:

```
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
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()
```

In [16]:

```
plt.plot(y,z)
plt.axis('equal')
```

Out[16]:

In [17]:

```
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)')
```

Out[17]:

`Sympy`

for routine problem solving.

In [19]:

```
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')
```

Out[19]:

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.

**Introduction to Python for Science**

This excellent introduction to python is aimed at undergraduates in science with no programming experience. It is free and available at the following link.

**Tutorial Introduction to Python for Science and Engineering.**

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.

- A Primer on Scientific Programming with Python (Fourth Edition) by Hans Petter Langtangen. 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.

- pycse - Python Computations in Science and Engineering by John Kitchin at Carnegie Mellon. This is a link into the the github repository for pycse, click on the
`Raw`

button to download the`.pdf`

file.

**Interative learning and on-line tutorials**

- Code Academy on Python
- Khan Academy Videos on Python Programming
- Python Tutorial
- Think Python: How to Think Like a Computer Scientist
- Engineering with Python

**Official documentation, examples, and galleries.**

In [ ]:

```
```