Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli

Installation

There are two options this semester for getting the necessary software:

  1. Install on your own machine
  2. Use a cloud computing platform

Your Own Machine

The easiest way to install all the components you will need for the class is to use Continuum Analytics' Anaconda distribution. We will be using python 2.7.x for all in class demos and homework so I strongly suggest you do not get the Python 3.4 version.

Alternatives to using Anaconda also exist in the form of Enthought's Canopy distribution which provides all the tools you will need as well along with an IDE (development environment).

Cloud Computing

Instead of running things locally on your machine there are a number of cloud services that you are welcome to use in order to get everything running easily.

  1. Sage-Math-Cloud - Create an account on Sage-Math-Cloud and interact with python via the provided terminal or Ipython notebook inteface.
  2. Wakari - Continuum also has a free cloud service called Wakari that you can sign up for which provides an Anaconda installation along with similar tools to Sage-Math-Cloud.

Basic Python

Python is a dynamic, interpreted language used throughout computational engineering and science. Due to its ease of use, cost, and available tools we will be learning the material in this course using Python tools exclusively. For those who are coming in without prior Python knowledge but a strong programming background this lecture should acquaint you with the basics. For people who do not know Python and do not have a strong programming background it is strongly recommended that you take the time to look through the other tutorials mentioned above.

Math

Basic math in Python is fairly straight forward with all the usual types of operations (+, -, *, /, **) which are addition, subtraction, multiplication, division and power. Note that in Python though we need to be careful about the types of numbers we use.


In [1]:
1 / 2

Python returns the floor of the 1 / 2 because we gave it integers to divide. It then interprets the result as also needing to be an integer. If one of the numbers was a decimal number we would have a decimal number as a result (really these are floating point numbers float).


In [2]:
1. / 2

In compound statements it can become more difficult to figure out where possible rounding might occur so be careful when you evaluate statements.


In [3]:
4. + 4.0**(3.0/2)

Python also understands imaginary numbers:


In [4]:
4 + 3j

Some of the more advanced mathematical functions are stored in modules. In order to use these functions we must first import them into our notebook and then use them.


In [5]:
import math

In [6]:
math?

In [7]:
math.sqrt(2.0)

In [8]:
math.sin(math.pi / 2.0)

In [9]:
from math import *
sin(pi)

Variables

Variables are defined and assigned to like many other languages.


In [10]:
num_students = 80
room_capacity = 85
(room_capacity - num_students) / room_capacity * 100.0

Note that we do not get what we expect from this expression as we expected from above. What would we have to change to get this to work?

We could go back to change our initializations but we could also use the function float to force these values to be of float type:


In [11]:
float(room_capacity - num_students) / float(room_capacity) * 100.0

Control Flow

if statements are the most basic unit of logic and allows us to conditionally operate on things.


In [12]:
x = 4
if x > 5:
    print "x is greater than 5"
elif x < 5:
    print "x is less than 5"
else:
    print "x is equal to 5"

for allows us to repeat tasks over a range of values or objects.


In [13]:
for i in range(5):
    print i

In [14]:
for i in range(3,7):
    print i

In [15]:
for animal in ['cat', 'dog', 'chinchilla']:
    print animal

In [16]:
for n in range(2, 10):
    is_prime = True
    for x in range(2, n):
        if n % x == 0:
            print n, 'equals', x, '*', n / x
            is_prime = False
            break
    if is_prime:
        print "%s is a prime number" % (n)

Functions

Functions are a fundamental way in any language to break up the code into pieces that can be isolated and repeatedly used based on their input.


In [17]:
def my_print_function(x):
    print x

my_print_function(3)

In [18]:
def my_add_function(a, b):
    return a + b, b

my_add_function(3.0, 5.0)

In [19]:
def my_crazy_function(a, b, c=1.0):
    d = a + b**c
    return d

my_crazy_function(2.0, 3.0), my_crazy_function(2.0, 3.0, 2.0), my_crazy_function(2.0, 3.0, c=2.0)

In [20]:
def my_other_function(a, b, c=1.0):
    return a + b, a + b**c, a + b**(3.0 / 7.0)

my_other_function(2.0, 3.0, c=2.0)

In [21]:
def fibonacci(n):
    """Return a list of the Fibonacci sequence up to n"""
    values = [0, 1]
    while values[-1] <= n:
        values.append(values[-1] + values[-2])
        print values
    return values

fibonacci(100)
fibonacci?

NumPy

The most important part of NumPy is the specification of an array object called an ndarray. This object as its name suggests stores array like information in multiple dimensions. These objects allow a programmer to access the data in a multitude of different ways as well as create common types of arrays and operate on these arrays easily.


In [22]:
import numpy

Constructors

Ways to make arrays in NumPy.


In [23]:
my_array = numpy.array([[1, 2], [3, 4]])
print my_array

In [24]:
numpy.linspace(-1, 1, 10)

In [25]:
numpy.zeros([3, 3])

In [26]:
numpy.ones([2, 3, 2])

In [27]:
numpy.empty([2,3])

Access

How do we access data in an array?


In [28]:
my_array[0, 1]

In [29]:
my_array[:,0]

In [30]:
my_vec = numpy.array([[1], [2]])
print my_vec

In [31]:
numpy.dot(my_array, my_vec)
numpy.cross?

In [32]:
my_array * my_vec

Manipulations

How do we manipulate arrays beyond indexing into them?


In [33]:
A = numpy.array([[1, 2, 3], [4, 5, 6]])
print "A Shape = ", A.shape
print A

In [34]:
B = A.reshape((6,1))
print "A Shape = ", A.shape
print "B Shape = ", B.shape
print B

In [35]:
numpy.tile(A, (2,2))

In [36]:
A.transpose()

In [37]:
A = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
print A
print A.shape

In [38]:
B = numpy.arange(1,10)
print B
print B.reshape((3,3))
B.reshape?
C = B.reshape((3,3))

In [39]:
print A * C

In [40]:
numpy.dot(A, C)

Mathematical Functions


In [41]:
x = numpy.linspace(-2.0 * numpy.pi, 2.0 * numpy.pi, 62)
y = numpy.sin(x)
print y

In [42]:
x = numpy.linspace(-1, 1, 20)
numpy.sqrt(x)

In [43]:
x = numpy.linspace(-1, 1, 20, dtype=complex)
numpy.sqrt(x)

Linear Algebra

Some functions for linear algebra available in NumPy. Full implementation in scipy.linalg.


In [44]:
numpy.linalg.norm(x)
numpy.linalg.norm?

In [45]:
M = numpy.array([[0,2],[8,0]])
b = numpy.array([1,2])
print M
print b

In [46]:
x = numpy.linalg.solve(M,b)
print x

In [47]:
lamda,V = numpy.linalg.eig(M)
print lamda
print V

SciPy

NumPy contains the basic building blocks for numerical computing where as the SciPy packages contain all the higher-level functionality. Refer to the SciPy webpage for more information on what it contains. There are also a number of SciKits which provide additional functionality

Matplotlib

The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figures. If you are interested in learning more about matplotlib or are looking to see how you might create a particular plot check out the matplotlib gallery for inspiration.

Refer to the APAM 4300 Notes on matplotlib for detailed examples.

Jupyter Notebooks

All class notes and assignments will be done within Jupyter notebooks (formally IPython notebooks). It is important that you become acquainted with these as there are a couple of pitfalls that you should be aware of.

  • Before turning in an assignment make sure to go to the "Kernel" menu and restart the notebook. After this select "Run All" from the "Cell" menu to rerun everything. This will ensure that you have properly defined everything in your notebook and have not accidentally erased a variable definition.
  • Use version 4.0 of the notebook so as not to run into problems with deleting notebook cells.

Code Styling

Very important in practice to write readable and understandable code. Here are a few things to keep in mind while programming in and out of this class, we will work on this actively as the semester progresses as well. The standard for which Python program are written to is called PEP 8 and contains the following basic guidelines:

  • Use 4-space indentation, no tabs
  • Wrap lines that exceed 80 characters
  • Use judicious use of blank lines to separate out functions, classes, and larger blocks of contained code
  • Comment! Also, put comments on their own line when possible
  • Use docstrings (function descriptions)
  • Use spaces around operators and after commas, a = f(1, 2) + g(3, 4)
  • Name your classes and functions consistently.
    • Use CamelCase for classes
    • Use lower_case_with_underscores for functions and variables
  • When in doubt be verbose with your comments and names of variables, functions, and classes

Good coding style will mean that we can more easily grade your assignments and understand what you are doing. Please make sure to keep this in mind especially when naming variables, making comments, or documenting your functions.