{ "metadata": { "name": "01-intro_master" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This material assumes that you have programmed before. This first lecture provides a quick introduction to programming in Python for those who either haven't used Python before or need a quick refresher.\n", "\n", "Let's start with a hypothetical problem we want to solve. We are interested in understanding the relationship between the weather and the number of mosquitos occuring in a particular year so that we can plan mosquito control measures accordingly. Since we want to apply these mosquito control measures at a number of different sites we need to understand both the relationship at a particular site and whether or not it is consistent across sites. The data we have to address this problem comes from the local government and are stored in tables in comma-separated values (CSV) files. Each file holds the data for a single location, each row holds the information for a single year at that location, and the columns hold the data on both mosquito numbers and the average temperature and rainfall from the beginning of mosquito breeding season. The first few rows of our first file look like:\n", "\n", "~~~\n", "\n", "year,temperature,rainfall,mosquitos\n", "\n", "2001,87,222,198\n", "2002,72,103,105\n", "2003,77,176,166\n", "\n", "~~~" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Objectives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Conduct variable assignment, looping, and conditionals in Python\n", "* Use an external Python library\n", "* Read tabular data from a file\n", "* Subset and perform analysis on data\n", "* Display simple graphs" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Loading Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many ways to read in data. The most basic reads in each line as a string." ] }, { "cell_type": "code", "collapsed": false, "input": [ "ofile = open('mosquito_data_A1.csv', 'r')\n", "print ofile.read()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "year,temperature,rainfall,mosquitos\n", "2001,87,222,198\n", "2002,72,103,105\n", "2003,77,176,166\n", "2004,89,236,210\n", "2005,88,283,242\n", "2006,89,151,147\n", "2007,71,121,117\n", "2008,88,267,232\n", "2009,85,211,191\n", "2010,75,101,106\n", "\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "An easier way to read files, especially in a uniform format is to use a package called numpy which incidentially is also used for array and matrix manipulation. Python has some built in abilities, but much of the flexibility of python comes from the ability to load different packages. To load a package:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will now use numpy to read our file. Many text reading options exist including pandas and astropy.io.ascii. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "np.genfromtxt('mosquito_data_A1.csv', unpack = True, skiprows = 1, delimiter = ',')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 3, "text": [ "array([[ 2001., 2002., 2003., 2004., 2005., 2006., 2007., 2008.,\n", " 2009., 2010.],\n", " [ 87., 72., 77., 89., 88., 89., 71., 88.,\n", " 85., 75.],\n", " [ 222., 103., 176., 236., 283., 151., 121., 267.,\n", " 211., 101.],\n", " [ 198., 105., 166., 210., 242., 147., 117., 232.,\n", " 191., 106.]])" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `genfromtext` function belongs to the `numpy` library. In order to run it we need to tell Python that it is part of `numpy` and we do this using the dot notation, which is used everywhere in Python to refer to parts of larger things.\n", "\n", "When we are finished typing and press Shift+Enter, the notebook runs our command and shows us its output. In this case, the output is the data we just loaded.\n", "\n", "We gave the genfromtxt function a few different pieces of information. \n", "\n", "First we gave it the name of the file to read. Notice this is the only information that does not have a word = X format. That means this is required and has no default value. \n", "\n", "Next we said unpack = True, this means we want each column to go to a separate array, not each line. \n", "\n", "skiprows = 1: there is text in the first row, so we want to skip it\n", "\n", "delimiter = ',': since this is a csv file, rows are separated by commas. The default for numpy.genfromtxt is tab separated.\n", "\n", "Our call to `numpy.genfromtxt` read data into memory, but didn't save it anywhere. To do that, we need to assign the array to a variable. In Python we use `=` to assign a new value to a variable like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = np.genfromtxt('mosquito_data_A1.csv', skiprows = 1, delimiter = ',', unpack = True)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This statement doesn't produce any output because assignment doesn't display anything. If we want to check that our data has been loaded, we can print the variable's value:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print d" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[ 2001. 2002. 2003. 2004. 2005. 2006. 2007. 2008. 2009. 2010.]\n", " [ 87. 72. 77. 89. 88. 89. 71. 88. 85. 75.]\n", " [ 222. 103. 176. 236. 283. 151. 121. 267. 211. 101.]\n", " [ 198. 105. 166. 210. 242. 147. 117. 232. 191. 106.]]\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "`print d` tells Python to display the text. Alternatively we could just include `data` as the last value in a code cell:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A word on variable names. The variable name I've chosen for the data doesn't really communicate any information to anyone about what it's holding,\n", "which means that when I come back to my code next month to change something I'm going to have a more difficult time understanding what the code is actually doing.\n", "This brings us to one of our first major lessons for the morning,\n", "which is that in order to understand what our code is doing so that we can quickly make changes in the future,\n", "we need to *write code for people, not computers*,\n", "and an important first step is to *use meaningful varible names*." ] }, { "cell_type": "code", "collapsed": false, "input": [ "data = np.genfromtxt('mosquito_data_A1.csv', skiprows = 1, delimiter = ',', unpack = True)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's deconstruct that statement:\n", "\n", "* The first argument in the function genfromtxt is the name of the file. This is required. One way you can tell is that it doesn't say x = Y like all of the other arguments\n", "* skiprows = 1: this is to tell genfromtxt how many rows to skip because they contain header information - we are skipping 1 row. This does have the format X = Y. This is called a keyword argument and it is optional. This means that there is a default value if you don't include it\n", "* delimiter = ',': this says that columns are separated by commas. The default behavior is to separate by tabs\n", "* unpack = True: this tells numpy that you want the information organized first by column, then by row." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's talk a little more about unpacking" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a, b, c = [1, 2, 3]\n", "print a\n", "print b" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1\n", "2\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's unpack data" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = data" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "print year" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 2001. 2002. 2003. 2004. 2005. 2006. 2007. 2008. 2009. 2010.]\n" ] } ], "prompt_number": 9 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Common Containers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once we have imported the data we can start doing things with it. First, let's ask what type of thing `data` refers to:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print type(temperature)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "type() asks the variable temperature what variable type it is (float, interger, list, dictionary, ...)\n", "temperature is a numpy array. What can you do to a numpy array?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print temperature * 4" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 348. 288. 308. 356. 352. 356. 284. 352. 340. 300.]\n" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "print temperature + temperature" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 174. 144. 154. 178. 176. 178. 142. 176. 170. 150.]\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "in general operations are done element wise in an array. There is also a matrix object if you need to do linear algebra. Another very common type is a list. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_list = [1, 2, 3, 'a', 'c']\n", "print type(my_list)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try the same operations on a list" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print my_list * 4" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 3, 'a', 'c', 1, 2, 3, 'a', 'c', 1, 2, 3, 'a', 'c', 1, 2, 3, 'a', 'c']\n" ] } ], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "SURPRISE! This repeated the list 4 times." ] }, { "cell_type": "code", "collapsed": false, "input": [ "print my_list + [4]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 3, 'a', 'c', 4]\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here the + acted as an append. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Differences between list and arrays:\n", "\n", "* A list can have mixed types (floats, ints, strings, other lists), a numpy array cannot. This is part of the reason why some matematical operations only work on numpy arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice I cheated a little. What if we just try to add a number?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print my_list + 4" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate list (not \"int\") to list", "output_type": "pyerr", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mmy_list\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: can only concatenate list (not \"int\") to list" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We got an error message. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Error Messages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how helpful this error message is:\n", "\n", "* It tells you what kind of error you got: in this case a TypeError\n", "* You get a useful error message telling you that you cannot combine a list with an integer\n", "* There is an -----> pointing to the offending line" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Accessing Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "so far we have printed the whole array - but what if we only want part of an array? We index" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print year\n", "print year[0]\n", "print year[2:5]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Important things to notice:\n", "\n", "* First, Python indexing starts at zero. In contrast, programming languages like R and MATLAB start counting at 1, because that's what human beings have done for thousands of years. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because that's simpler for computers to do. This means that if we have 5 things in Python they are numbered 0, 1, 2, 3, 4, and the first row in a data frame is always row 0.\n", "* the final array includes the starting index and excludes the ending index. This says start with the 3rd element (index 2) and got to (but don't include) the 6th element (index 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Being lazy (aka awesome)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the first 3 elements" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print year[:3]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print from the 3rd element to the end" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print year[2:]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the last 3 elements" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print year[-3:]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is awesome because you don't have to know how long your array is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Methods and Objects" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is an object oriented language which means that everything is an object. Objects know things about themselves and can sometimes perform simple operations on themselves. What does that mean in practice? " ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 2" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "dir(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here x is just an integer, but it knows how to add with other object (__add__), you can ask it its bit_length, conjugate, etc. So it is not just an integer, it is an object" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print x.bit_length()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You will notice that some of these methods and attributes have __ or _ and some do not. In general the ones with nothing are for common use and the ones with _ and __ you won't need unless you are trying to do something really funky - like redefine what integer addition means." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So what can you do to arrays?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print temperature.mean()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "arrays have lots of useful methods. In addition to the dir() function, in ipython you can also type variable. to get a list of options" ] }, { "cell_type": "code", "collapsed": true, "input": [ "print data." ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print year.min()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can even operate on a piece of an array" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print mosquitos[1:3].std()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Challenge" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import the data from `mosquito_data_A2.csv`, create new variables that hold the arrays, and print the means and standard deviations for the weather variables (rainfall and temperature)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Solution" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = np.genfromtxt('mosquito_data_A1.csv', skiprows = 1, delimiter = ',', unpack = True)\n", "print temperature.mean()\n", "print temperature.std()\n", "print rainfall.mean()\n", "print rainfall.std()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once we have some data we often want to be able to loop over it to perform the same operation repeatedly.\n", "A `for` loop in Python takes the general form\n", "\n", "~~~\n", "\n", "for item in list:\n", "\n", " do_something\n", "\n", "~~~\n", "\n", "So if we want to loop over the temperatures and print out there values in degrees Celcius (instead of Farenheit) we can use:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for temp_in_f in temperature:\n", " temp_in_c = (temp_in_f - 32) * 5 / 9.0\n", " print temp_in_c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That looks good, but why did we use 9.0 instead of 9? The reason is that computers store integers and numbers with decimals as different types: integers and floating point numbers (or floats). Addition, subtraction and multiplication work on both as we'd expect, but division works differently. If we divide one integer by another, we get the quotient without the remainder:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print '10/3 is:', 10 / 3" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If either part of the division is a float, on the other hand, the computer creates a floating-point answer:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print '10/3.0 is:', 10 / 3.0" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The computer does this for historical reasons: integer operations were much faster on early machines, and this behavior is actually useful in a lot of situations. However, it's still confusing, so Python 3 produces a floating-point answer when dividing integers if it needs to. We're still using Python 2.7 in this class, so if we want 5/9 to give us the right answer, we have to write it as 5.0/9, 5/9.0, or some other variation." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Conditionals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The other standard thing we need to know how to do in Python is conditionals, or if/then/else statements. In Python the basic syntax is:\n", "\n", "~~~\n", "\n", "if condition:\n", "\n", " do_something\n", "\n", "~~~\n", "\n", "So if we want to loop over the temperatures and print out only those temperatures that are greater than 80 degrees we would use:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "if temperature[0] > 80:\n", " print \"The temperature is greater than 80\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use `==` for equality, `<=` for less than or equal to, `>=` for greater than or equal to, and `!=` for not equal to.\n", "\n", "Additional conditions can be handled using `elif` and `else`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "if temperature[0] < 87:\n", " print \"The temperature is < 87\"\n", "elif temperature[0] > 87:\n", " print \"The temperature is > 87\"\n", "else:\n", " print \" The temperature is equal to 87\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Challenge" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import the data from `mosquito_data_A2.csv` and loop over the temperature values. For each temperature print out whether it is greater than the mean, less than the mean, or equal to the mean." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Solution" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = np.genfromtxt('mosquito_data_A1.csv', skiprows = 1, delimiter = ',', unpack = True)\n", "for temp in temperature:\n", " if temp > temperature.mean():\n", " print 'temp is greater than mean'\n", " elif temp < temperature.mean():\n", " print 'temp is less than mean'\n", " else:\n", " print 'temp is equal to mean'" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#Key Points\n", "\n", "* Import a library into a program using `import libraryname`.\n", "* Use the `numpy` library to work with data tables in Python.\n", "* Use `variable = value` to assign a value to a variable.\n", "* Use `print something` to display the value of `something`.\n", "* Use `array[start_row:stop_row]` to select rows from a data frame.\n", "* Indices start at 0, not 1.\n", "* Use `array.mean()` and `array.min()` to calculate simple statistics.\n", "* Use `for x in list:` to loop over values\n", "* Use `if condition:` to make conditional decisions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#Modularization and Documentation\n", "\n", "Now that we've covered some of the basic syntax and libraries in Python we can start to tackle our data analysis problem.\n", "We are interested in understanding the relationship between the weather and the number of mosquitos so that we can plan mosquito control measures.\n", "Since we want to apply these mosquito control measures at a number of different sites we need to understand how the relationship varies across sites.\n", "Remember that we have a series of CSV files with each file containing the data for a single location." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Objectives\n", "\n", "* Write code for people, not computers\n", "* Break a program into chunks\n", "* Write and use functions in Python\n", "* Write useful documentation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Starting small" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When approaching computational tasks like this one it is typically best to start small,\n", "check each piece of code as you go,\n", "and make incremental changes.\n", "This helps avoid marathon debugging sessions\n", "because it's much easier to debug one small piece of the code at a time than to write 100 lines of code and\n", "then try to figure out all of the different bugs in it.\n", "\n", "Let's start by reading in the data from a single file and conducting a simple regression analysis on it." ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = np.genfromtxt('mosquito_data_A1.csv', skiprows = 1, delimiter = ',', unpack = True)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What does our data look like?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Plotting" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from matplotlib import pyplot" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case pyplot is a submodule of matplotlib. I know that everything I want to do is in pyplot, so instead of typing matplotlib.pyplot for everything, I can import this way and just type pyplot" ] }, { "cell_type": "code", "collapsed": false, "input": [ "pyplot.plot(temperature, mosquitos)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That looks pretty ugly, let's make points instead of lines" ] }, { "cell_type": "code", "collapsed": false, "input": [ "pyplot.cla()\n", "pyplot.plot(temperature, mosquitos, 'o')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ohhh, that looks like a straight line, let's see if we can fit it using the numpy polyfit function" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fit_coeff = np.polyfit(temperature, mosquitos, 1)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here I am giving polyfit the independent variable (rainfall), the dependent variable (mosquitos), and the order of the polynomial to fit (here 1 since its a line). This returns the coefficients of the fit starting with the highest order first" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print fit_coeff" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can plot the fit" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fit_to_data = fit_coeff[0] * temperature + fit_coeff[1]\n", "pyplot.plot(temperature, fit_to_data)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interactive plotting:\n", "\n", "* Save\n", "* Zoom\n", "* Pan\n", "* reset\n", "* awesomeness" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Modularization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So now I've done a few things interactively:\n", "\n", "1. Read in a CSV file of year, temperature, rainfall, and number of mosquitos\n", "2. Convert temperature to celsius\n", "3. Plot data\n", "\n", "This could all go into a single function but that has a few disadvantages\n", "1. It makes it harder to test because you have to test everything together rather than a specific task\n", "2. It makes it harder to debug - if something breaks you have to figure out where in you single function that breaking happened rather than being pointed to specific function\n", "3. It makes it harder to read your code. Imagine reading a book with no paragraphs... breaking your code into smaller pieces makes your code more readable.\n", "4. It is hard to reuse your functions. It is unlikely that you will have to write code for this exact file format, but it is probably very likely that you will have to convert to celsius again. Smaller building blocks are much easier to reuse than a single large, specific program\n", "\n", "Think of breaking your program into steps, just like we did above\n", "\n", "Functions are the paragraphs of programming and the function name is the topic sentence, just like variables these should be very descriptive. Functions take the general form:\n", "\n", "def function_name:\n", "\n", " do stuff\n", "\n", " return result\n", "\n", "We'll start with some pseudo code" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def read_csv_file():\n", " '''\n", " This code will read in a CSV file of year, temperature, rainfall, and number of mosquitos and return 4 arrays, one for each column\n", " '''\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "def convert_fahrenheit_to_celsius():\n", " '''\n", " This code will convert an array of tempertures from fahrenheit to celsius\n", " '''\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "def plot_data():\n", " '''\n", " This code will plot the arrays in x and y with symbol (default \"o\")\n", " '''\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is pseudo code. It doesn't do anything, but I now have a skeleton of my program and I just have to fill in the information.\n", "\n", "I used triple quotes, aka doc string to describe the code. There is a help function that can be called on any function which gives you information on that function. By default the help function returns the doc string." ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(plot_data)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "help(np.polyfit)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "my main code will look like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "read_csv_file()\n", "convert_fahrenheit_to_celsius()\n", "plot_data()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's fill in the details, starting with the first function" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def read_csv_file(filename):\n", " '''\n", " This code will read in a CSV file of year, temperature, rainfall, and number of mosquitos and return 4 arrays, one for each column\n", " '''\n", " year, temperature, rainfall, mosquitos = np.genfromtxt(filename, skiprows = 1, delimiter = ',', unpack = True)\n", " return year, temperature, rainfall, mosquitos\n", "\n", "def convert_fahrenheit_to_celsius():\n", " '''\n", " This code will convert an array of tempertures from fahrenheit to celsius\n", " '''\n", " pass\n", "\n", "def plot_data():\n", " '''\n", " This code will plot the arrays in x and y with symbol (default \"o\")\n", " '''\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's test our first function" ] }, { "cell_type": "code", "collapsed": false, "input": [ "read_csv_file('mosquito_data_A1.csv')\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That looks good, but it is just returning arays that are not assigned to variables outside the function so we can't use them. Let's assign them" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = read_csv_file('mosquito_data_A1.csv')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print year" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Excellent, now let's convert to fahenheit" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def read_csv_file(filename):\n", " '''\n", " This code will read in a CSV file of year, temperature, rainfall, and number of mosquitos and return 4 arrays, one for each column\n", " '''\n", " year, temperature, rainfall, mosquitos = np.genfromtxt(filename, skiprows = 1, delimiter = ',', unpack = True)\n", " return year, temperature, rainfall, mosquitos\n", "\n", "def convert_fahrenheit_to_celsius(temp_in_f):\n", " '''\n", " This code will convert an array of tempertures from fahrenheit to celsius\n", " '''\n", " temp_in_c = (temp_in_f - 32) * 5 / 9.0\n", " return temp_in_c\n", "\n", "def plot_data():\n", " '''\n", " This code will plot the arrays in x and y with symbol (default \"o\")\n", " '''\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = read_csv_file('mosquito_data_A1.csv')\n", "temp_in_c = convert_fahrenheit_to_celsius(temperature)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print temperature, temp_in_c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Challenge\n", "Write the plotting function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Solution" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def plot_data(x, y, symbol = 'o'):\n", " '''\n", " This code will plot the arrays in x and y with symbol (default \"o\")\n", " '''\n", " pyplot.plot(x, y, symbol)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice this function does not have to return anything" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One final command: to save a figure from the command line (i.e. not using the GUI)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "pyplot.savefig('temp_vs_mosquitos.pdf')\n", "pyplot.close()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "savefig will save to the current directory unless you give it a path. It is smart enough to figure out your file format from the extension of the file you save. You can also save png files, jpg files, ps files, etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's add this to our plot_data function" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def plot_data(x, y, symbol = 'o'):\n", " '''\n", " This code will plot the arrays in x and y with symbol (default \"o\")\n", " '''\n", " pyplot.plot(x, y, symbol)\n", " pyplot.savefig('temp_vs_mosquitos.pdf')\n", " pyplot.close()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, let's run our whole program" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year, temperature, rainfall, mosquitos = read_csv_file('mosquito_data_A1.csv')\n", "temp_in_c = convert_fahrenheit_to_celsius(temperature)\n", "plot_data()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Moving out of the notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* In the shell cd to the intermediate/python directory\n", "* open nano\n", "* Copy and paste your functions into nano. At the bottom, not indented, put the calls to the functions\n", "* Save your file as plot_temperature.py\n", "* start an ipython session\n", "* import plot_temperature.py\n", "* from the shell type python plot_temperature.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show if __name__ == \"__main__\":" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Repeat:\n", "\n", " import\n", "\n", " run from shell" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }