#!/usr/bin/env python # coding: utf-8 # ###### The latest version of this IPython notebook is available at [http://github.com/jckantor/ESTM60203](http://github.com/jckantor/ESTM60203) for noncommercial use under terms of the [Creative Commons Attribution Noncommericial ShareAlike License (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/). # J.C. Kantor (Kantor.1@nd.edu) # # Getting Started with IPython # The purpose of this [IPython notebook](http://ipython.org/notebook.html) is to get you started in using Python (actually, the interactive variant called IPython)calculations assuming this is your first exposure to Python. # ### Initializations # In[1]: from IPython.core.display import HTML HTML(open("styles/custom.css", "r").read()) # ## Step 0: Install IPython # The first step is to obtain a working IPython environment. The easiest approach is to sign up for a free account on a cloud-based service such as [Wakari.io](https://www.wakari.io/). You'll need internet connectivity to access your work, but there's nothing to install, no software to maintain, and you can work with nothing more than a browser on a Chromebook or tablet. # # Alternatively, you can install an IPython environment on your laptop. There are at least two excellent and free packages available: # # * [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/) # # 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. You should allow about 10-30 minutes for the installation depending on your experience and 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 # ## Step 1: Start an IPython Notebook Session # IPython notebooks (like this one) are simply files in a directory with a `.ipynb` suffix. They can be stored in any directory, including a Dropbox or Google Drive directory. # # 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 --pylab=inline # # 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[2]: from IPython.display import YouTubeVideo YouTubeVideo("H6dLGQw9yFQ",560,315) # ## Step 2: Experiment with Python # 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 # Basic arithmetic functions # In[1]: a = 12 b = 2 print "a + b = ", a + b print "a**b = ", a**b print "a/b = ", a/b # Calling a builtin function # In[2]: sin(2*pi) # ### Working with 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[3]: xList = [1, 2, 3, 4] print xList # In[4]: # Concatenation x = [1, 2, 3, 4]; y = [5, 6, 7, 8]; x + y # In[5]: # Two ways to sum a list of numbers print sum(x) print reduce(add,x) # In[6]: # Two ways to add a two lists of numbers print add(x,y) print map(add,x,y) # 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[7]: for x in xList: print "x =",x, " sin(x) = ", sin(x) # ### Working with 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[8]: mw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01} print mw # We can a value to an existing dictionary. # In[9]: mw['C8H18'] = 114.23 print mw # We can retrieve a value from a dictionary. # In[10]: mw['CH4'] # A for loop is a useful means of interating over all key-value pairs of a dictionary. # In[11]: for species in mw.keys(): print "The molar mass of {:7.2f}".format(species, mw[species]) # In[13]: for species in sorted(mw, key = mw.get): print " {:<8s} {:>7.2f}".format(species, mw[species]) # ### Plotting # IPython notebooks include plotting functionality very similar to Matlab's. Here are some examples. # In[14]: x = linspace(0,10) y = sin(x) z = cos(x) plot(x,y,'b',x,z,'r') xlabel('Radians'); ylabel('Value'); title('Plotting Demonstration') legend(['Sin','Cos']) grid() # In[15]: plot(y,z) axis('equal') # In[16]: subplot(2,1,1) plot(x,y) title('Sin(x)') subplot(2,1,2) plot(x,z) title('Cos(x)') # ## Step 3: Solve 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[17]: 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 and select the first solution f = sym.solve(eqn,P)[0] # Use the sympy plot function to plot sym.plot(f,(V,1,10),xlabel='Volume m**3',ylabel='Pressure Pa') # ## Step 4: 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 # # Interative learning # # * [Code Academy on Python](http://www.codecademy.com/tracks/python) # # On-line tutorials, books, etc. # # * [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) # # Books # # * [Learn Python the Hard Way](http://learnpythonthehardway.org/book/) # # 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) # # Engineering applications # # * [Engineering with Python](http://www.engineeringwithpython.com/) # # In[ ]: