{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following is a brief introduction to Python and the IPython Notebook. There is much more to learn than what is covered here. This is just enough to get you started with the tutorial." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The IPython Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "IPython consists of two processes: a kernel and a frontend. The kernel executes code while the frontend provides an interface for the user enter their code. The IPython notebook is a frontend for Python which provides an interactive web-environment for executing code and displaying rich media." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using the Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To start an IPython notebook session open a command prompt, navigate to a desired working directory then issue the following command:\n", "\n", "`ipython notebook`\n", "\n", "A new window will open in your web browser where you can open an existing notebook or start a new one.\n", "Notebooks are organized with cells. You may have a code cell for inputing commands followed by its result cell which contains the output of the code. You may also have a text cell, such as this one you're reading right now. Cell type can be changed in the above dropdown menu.\n", "\n", "There is the menubar above for navigating a notebook but you will find the following shortcuts helpful:\n", "\n", "- `Enter` : Create a new line with in cell\n", "- `Shift + Enter` : Execute cell and advance to next cell\n", "- `Ctrl + Enter` : Execute cell in place (do not advance to the next cell)\n", "- Press `esc` (command mode) then `h` to display keyboard shortcuts\n", "\n", "At times you might run code that gets stuck in an infinite loop or simply you want to clear all your workspace variables and start over. To solve each of these problems you can click on the menu:\n", "\n", "`Kernel -> Interrupt`\n", "\n", "`Kernel -> Restart`\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from __future__ import print_function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Magic Commands" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are commands to control IPython itself." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# list available magic commands\n", "%lsmagic" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%load utils.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Need Help?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In case you're lost help isn't far. The following commands should provide assistance." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Displays an overview of IPython's features\n", "?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# A Quick Reference for IPython\n", "%quickref" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For details about an object\n", "# object_name?\n", "round??" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# list functions available in your workspace\n", "dir()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# list variables available in your workspace\n", "%whos" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic Data Types" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = 5\n", "b = 5.0\n", "c = float(5)\n", "d = 'dee'\n", "e = 'e'\n", "\n", "type(a), type(b), type(c), type(d), type(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Data Structures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python offers several builtin data structures for arranging data in memory. We will be making use of lists, dictionaries, tuples during this tutorial. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list is a versatile container that holds objects in the order given. Lists are typically used to group similar items but may contain heterogenous data types." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "empty_list = []\n", "\n", "string_list = ['lions', 'tigers', 'bears', 'sharks', 'hamsters']\n", "\n", "int_list = [0, 1, 2, 3, 4]\n", "int_list2 = range(5,10)\n", "\n", "list_from_variables = [a,b,c,d,e]\n", "\n", "list_of_lists = [empty_list,\n", " string_list,\n", " list_from_variables,\n", " int_list,\n", " int_list2]\n", "\n", "print(list_of_lists)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Elements of a list are accessible by their index." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(string_list[0])\n", "print(string_list[1:4])\n", "print(int_list[::2]) # get every 2nd element\n", "print(list_of_lists[1][4]) # get a nested item" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "List are mutable, meaning after a list is created we can change, add, or remove elements." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "int_list[2] = 222\n", "\n", "int_list.append(5)\n", "\n", "string_list.remove('lions')\n", "\n", "list_from_variables.extend(int_list)\n", "\n", "print(int_list)\n", "print(string_list)\n", "print(list_from_variables)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples share similarites with lists. A tuple is good for organizing related data that may be of different types. Notice they are defined with parenthesis, `()`, rather than brackets." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "joe_blow = (32, 'tall', 'likes hats')\n", "\n", "print(joe_blow[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike lists, tuples are immutable. They cannot be changed once defined." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# this won't work\n", "joe_blow.append('married')\n", "\n", "# neither will this\n", "joe_blow[2] = 'not really a fan of hats'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In python a function can return multiple values. These ouputs are packed into a tuple. Tuple unpacking assigns individual elements of a tuple to separate variables." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pets = ('elephant', 'cow', 'rock')\n", "\n", "pet1, pet2, pet3 = pets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A peculiar thing about tuples in python is defining a single element tuple. Note the trialing comma. This is necessary for python to know you want a one-element tuple." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "(pet1,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A dictionary is an unordered set of *key:value* pairs. Much like a language dictionary where you look up a *word* and get its *definition* in a python dictionary you look up a *key* and get its *value*." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# numbers or strings may be used as keys\n", "dictionary0 = {'key1':'value1', 'key2':'value2', 'key3':'value3'}\n", "dictionary1 = {1:'value1', 2:'value2', 3:'value3'}\n", "\n", "cylinder = {'mass':50, 'base':10, 'height':100}\n", "\n", "print(dictionary0)\n", "print(dictionary1.keys())\n", "print(cylinder['mass'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The zip function is a convenient function to help generate a dictionary. It takes sequence objects and combines them into a list of tuples. We can subsequently use the list of two element tuples to create a dictionary." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "keys = ['mass01', 'inertia01', 'mass02', 'inertia02']\n", "values = [10, 1, 50, 5]\n", "\n", "dict(zip(keys, values))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python does not use braces, `{}`, or `end` statements to seperate blocks of code. Rather, code blocks are initialized with colon, `:`, and defined by their indentation. It is convention to use four spaces for each level of indentation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def abs_value(A):\n", " if A < 0:\n", " A = -A \n", " return A\n", "\n", "abs_value(-100)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def long_div(dividend, divisor):\n", " quotient = dividend // divisor # // : floor division\n", " remainder = dividend % divisor # % : modulo\n", " return quotient, remainder\n", "\n", "\n", "a = 430\n", "b = 25\n", "\n", "# an example of tuple unpacking\n", "quo, rem = long_div(a, b)\n", "\n", "print('%d divided %d is %d remainder %d' % (a, b, quo, rem))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Modules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Modules add additional functionality not present in the default installation of python. Throughout this tutorial we will either import an entire module or import specific functions from a module." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# import object from sympy into the current namespace\n", "from numpy import array\n", "\n", "# import multiple objects from sympy\n", "from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Objects from these modules are now available in your namespace." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# from numpy\n", "arr = array([1,2,3,4,5])\n", "\n", "# from sympy.physics.mechanics\n", "inertial_frame = ReferenceFrame('I')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The SciPy Stack" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SciPy is a collection of open source software that brings scientific computing to Python.\n", "\n", "- IPython : Enhanced Interactive Console\n", "- Numpy : N-dimensional array package\n", "- Matplotlib : a fully featured 2D plotting package\n", "- Scipy : a collection of toolboxes for signal processing, optimization, statisitics, etc.\n", "- Sympy : symbolic mathematics and computer algebra\n", "- and much more..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numpy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from numpy import random, linspace, zeros, arange" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating Arrays" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# An array from a list\n", "print(array([5, 12, -2, 9.3, 7]))\n", "\n", "# random values\n", "print(random.random((5)))\n", "\n", "# linearly spaced values\n", "# 5 values between 0 and 10 inclusive\n", "print(linspace(0,10,5))\n", "\n", "# range of values with a defined stepsize\n", "# start at 0 and increase by 3 \n", "print(arange(0,14,3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accessing Array Elements" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "P = random.random((3,5))\n", "\n", "# individual element\n", "print(P[0,3])\n", "\n", "# entire row\n", "print(P[2])\n", "\n", "# entire column\n", "print(P[:,4])\n", "\n", "# every third element\n", "print(P[::3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Operations on Arrays" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# mathematical operations are always elementwise\n", "x = arange(5)\n", "\n", "print(x)\n", "\n", "# the double asterisk represents exponentiation\n", "print(x + x**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Matplotlib provides an API similar to MATLAB's" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the magic command `%matplotlib inline` to work with matplotlib interactively. The `inline` argument allows for plots to be embedded within the IPython notebook" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.pyplot import plot, subplot, xlabel, ylabel, legend, tight_layout\n", "from numpy import sin, cos, pi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = arange(-pi,pi,0.1)\n", "y1 = 2*sin(x)\n", "y2 = x + cos(4*x)\n", "\n", "plot(x, y1, 'r', x, y2, '--b')\n", "plot(x[::5], y1[::5], 'og') # plot every 5th point\n", "xlabel('x axis')\n", "ylabel('y axis')\n", "legend(['red', 'blue', 'green'], loc='upper left')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = linspace(-100,100)\n", "\n", "for i in range(1,5):\n", " subplot(2,2,i)\n", " plot(x, x**i)\n", " \n", "tight_layout() # this prevents the axis labels from overlapping" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the provided function to create 3 different sine waves at various frequencies. Plot the 3 functions with labeled axis." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def three_sine_waves(t, A, B, C):\n", " \"\"\"\n", " t : (type: array) an monotonically increasing array of time values\n", " A,B,C : (type: float) frequency of sine waves\n", " \"\"\"\n", " y1 = sin(A*t)\n", " y2 = sin(B*t)\n", " y3 = sin(C*t)\n", " \n", " return y1, y2, y3" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "t = \n", "y1, y2, y3 = three_sine_waves()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%load exercise_solutions/n00_python_intro_data-plotting.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Scipy odeint" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Scipy provides a routine for integrating first order ordinary differential equations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy.integrate import odeint" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def dy(y,x):\n", " return x\n", "\n", "y0 = 0.0\n", "x = linspace(-5.0, 5.0, 1000)\n", "\n", "y = odeint(dy,y0,x)\n", "\n", "plot(x,y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def dy(y,t,coeff):\n", " A = coeff['A']\n", " B = coeff['B']\n", " C = coeff['C']\n", " D = coeff['D']\n", " return A*t**3 + B*t**2 + C*t + D\n", "\n", "y0 = 2.0\n", "t = linspace(-5.0, 3.0, 1000)\n", "sys = {'A' : 0.25,\n", " 'B' : 0.75,\n", " 'C' : -1.5,\n", " 'D' : -2.0}\n", "\n", "y = odeint(dy, y0, t, args=(sys,))\n", "\n", "plot(t,y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## SymPy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sympy import *\n", "\n", "# This is for prettier printing of equations\n", "interactive.printing.init_printing()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating Symbolic Variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = symbols('a')\n", "b = symbols('b')\n", "gravity, mass, spring_const, time = symbols('g, m, k, t')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Expressions Using Symbolic Variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a**2 + b/pi" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "simplify(4*(a*a*a)*(b+b+b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "diff(-gravity*time**2/2, time)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# indefinte integral\n", "\n", "integrate(-gravity,time)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# definite integral\n", "\n", "v0 = 5\n", "t1 = 0\n", "t2 = .35\n", "position = integrate(-gravity*time + v0,(time,t1,t2))\n", "position.subs(gravity, 9.81)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Additional Resources" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[1] http://docs.python.org/2/tutorial\n", "\n", "[2] http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Cell%20Magics.ipynb\n", "\n", "[3] http://www.scipy.org/index.html" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }