#!/usr/bin/env python # coding: utf-8 # # *This notebook contains course material from [CBE20255](https://jckantor.github.io/CBE20255) # by Jeffrey Kantor (jeff at nd.edu); the content is available [on Github](https://github.com/jckantor/CBE20255.git). # The text is released under the [CC-BY-NC-ND-4.0 license](https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode), # and code is released under the [MIT license](https://opensource.org/licenses/MIT).* # # < [Getting Started](http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/00.00-Getting-Started.ipynb) | [Contents](toc.ipynb) | [Solving Linear Equations with Simpy](http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/00.02-Solving-Linear-Equations-with-Sympy.ipynb) >

Open in Colab # # Jupyter Notebooks, Python, and Google Colaboratory # ## Summary # # The purpose of this notebook is to introduce Jupyter Notebooks, Python, and Google Colaboratory for routine engineering calculations. This introduction assumes this is your first exposure to these topics. # # **[Jupyter Notebooks](https://Jupyter.org)** are interactive documents, like this one, that include text and code. The documents are ordinary files with a suffix `.ipynb`. They can be uploaded, downloaded, and shared like any other digital document. The notebooks are composed of individual cells containing either text, code, or the output of a calculation. The code cells be written in different programming languages such as Python, R, and Julia. # # **[Python](https://www.python.org/)** is a high-level, object-oriented programming language well suited to the rapid development of web and scientific applications. It is widely used for interactive science and engineering computations where productivity is a more important than achieving the highest levels of numerical performance. Python refers to the language itself plus a large eco-system of development tools, documentation, and code libraries for numerical computations, data management, and graphics. # # **[Google Colaboratory](https://colab.research.google.com/)** is Google's cloud environment for viewing and executing Jupyter/Python notebooks. It operates like Google docs, providing for the collaborative creation and editing of notebooks, and allowing notebooks to be saved to your Google Drive account. Because Colaboratory is based entirely in the cloud, there is no need to install any local software. Colaboratory requires only a browser and internet access to view and execute notebooks. # # There other software development environments well suited to viewing and executing the notebooks in this repository. Among them are the excellent distributions # # * [Anaconda](https://store.continuum.io/cshop/anaconda/) available from [Continuum Analytics](http://continuum.io/). # * [Enthought Canopy](https://www.enthought.com/products/canopy/) available from [Enthought, Inc.](https://www.enthought.com/) # # which include tools to view and edit Jupyter notebooks, curated versions of all the major Python code libraries, and additional software development tools. You will want to install one of these distributions if you need off-line access to these notebooks, or if you intend to do more extensive development. # ## Setting up Google Colaboratory and Google Drive # # The easiest way to get started with Google Colaboratory is to open a notebook. If you are not currently reading this notebook on Colaboratory, open it [here from the github repository](https://colab.research.google.com/github/jckantor/CBE20255/blob/master/notebooks/Getting_Started_with_Jupyter_Notebooks_and_Python.ipynb). # # Google Colaboratory is tightly integrated with Google Drive. Notebooks can be opened directly from Google Drive and automatically saved back to Google Drive. Notebooks can be shared, and support mutiple users collaborating simultaenously the same notebook. These features will be familiar if you've previously used Google Docs. You can obtain a Google Drive or a Google One account [here](https://www.google.com/drive/) if you don't already have one. The free tier offers 15GB of storage which is enough for routine use of these notebooks. # # When opened from a third party resource such as github, the notebook is initially in `playground mode`. This is fine for viewing notebooks and executing code cells. To save your work you will need to save a copy of the notebook. You can save a copy to: # # * your Google Drive # * a repository in your own github account # * download the notebook to your personal device # # ## Python Basics # # 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. # ### Arithmetic Operations # Basic arithmetic functions # In[6]: a = 12 b = 2 print("a + b = ", a + b) print("a**b = ", a**b) print("a/b = ", a/b) # Most math functions are in the `numpy` library. This next cell shows how to import `numpy` with the prefix `np`, then use it to call a common function # In[7]: import numpy as np np.sin(2*np.pi) # ### Lists # Lists are a versatile way of organizing your data in Python. Here are some examples, more can be found on [this Khan Academy video](http://youtu.be/zEyEC34MY1A). # In[8]: xList = [1, 2, 3, 4] print(xList) # Concatentation is the operation of joining one list to another. # In[9]: # Concatenation x = [1, 2, 3, 4]; y = [5, 6, 7, 8]; x + y # A common operation is to apply a binary operation to elements of a single list. For an example such as arithmetic addition, this can be done using the `sum` function from `numpy`. # In[10]: # Two ways to sum a list of numbers print(np.sum(x)) # 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. # In[11]: for x in xList: print("x =", x, " sin(x) = ", np.sin(x)) # A **list comprehension** is a very useful tool for creating a new list using data from an existing. For example, suppose you have a list consisting random numbers # In[12]: from random import random [i + random() for i in range(0,10)] # ### Dictionaries # 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. # In[13]: mw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01} print(mw) # We can a value to an existing dictionary. # In[14]: mw['C8H18'] = 114.23 print(mw) # We can retrieve a value from a dictionary. # In[15]: mw['CH4'] # A for loop is a useful means of interating over all key-value pairs of a dictionary. # In[16]: for species in mw.keys(): print("The molar mass of {:7.2f}".format(species, mw[species])) # In[18]: for species in sorted(mw, key = mw.get): print(" {:<8s} {:>7.2f}".format(species, mw[species])) # ### Plotting # Importing the `matplotlib.pyplot` library gives IPython notebooks plotting functionality very similar to Matlab's. Here are some examples using functions from the # In[21]: import matplotlib.pyplot as plt import numpy as np get_ipython().run_line_magic('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(True) # In[22]: plt.plot(y,z) plt.axis('equal') # In[23]: 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)') # ## Solving Equations using Sympy # One of the best features of Python is the ability to extend it's functionality by importing special purpose libraries of functions. Here we demonstrate the use of a symbolic algebra package [`Sympy`](http://sympy.org/en/index.html) for routine problem solving. # In[24]: 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') # ## Defining your own Functions # # Many of the physical properties of chemical species are given as functions of temperature or pressure. # ## Learn More # 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. # ### Tutorial Introductions to Python for Science and Engineering # # This excellent introduction to python is aimed at undergraduates in science with no programming experience. It is free and available at the following link. # # * [Introduction to Python for Science](https://github.com/djpine/pyman) # # 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](http://library.nd.edu/eresources/access/acceptable_use.shtml). Others can find it at [Springer](http://www.springer.com/us/book/9783642549588) or [Amazon](http://www.amazon.com/Scientific-Programming-Computational-Science-Engineering/dp/3642549586/ref=dp_ob_title_bk). Resources for this book are available on [github](http://hplgit.github.io/scipro-primer/). # # * [A Primer on Scientific Programming with Python (Fourth Edition)](http://link.springer.com.proxy.library.nd.edu/book/10.1007/978-3-642-54959-5) by Hans Petter Langtangen. Resources for this book are available on [github](http://hplgit.github.io/scipro-primer/). # # 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](https://github.com/jkitchin/pycse/blob/master/pycse.pdf) by John Kitchin at Carnegie Mellon. This is a link into the the [github repository for pycse](https://github.com/jkitchin/pycse), click on the `Raw` button to download the `.pdf` file. # ### Interactive Learning and On-Line Tutorials # # * [Code Academy on Python](http://www.codecademy.com/tracks/python) # * [Khan Academy Videos on Python Programming](https://www.khanacademy.org/science/computer-science-subject/computer-science) # * [Python Tutorial](http://docs.python.org/2/tutorial/) # * [Think Python: How to Think Like a Computer Scientist](http://www.greenteapress.com/thinkpython/html/index.html) # * [Engineering with Python](http://www.engineeringwithpython.com/) # ### Official documentation, examples, and galleries # # * [Notebook Examples](https://github.com/ipython/ipython/tree/master/examples/notebooks) # * [Notebook Gallery](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks) # * [Official Notebook Documentation](http://ipython.org/ipython-doc/stable/interactive/notebook.html) # * [Matplotlib](http://matplotlib.org/index.html) # # < [Getting Started](http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/00.00-Getting-Started.ipynb) | [Contents](toc.ipynb) | [Solving Linear Equations with Simpy](http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/00.02-Solving-Linear-Equations-with-Sympy.ipynb) >

Open in Colab