︠9be24417-0a95-44e0-80af-1a794ed8c445i︠ %html

Resources for self-directed learning 

Things you are going to need to get started

Python basics

Python objects, Lists

︡c57809a0-5056-470e-a272-2a28d52e85d7︡{"html": "

Resources for self-directed learning 

\n\n\n\n

Things you are going to need to get started

\n\n\n\n

Python basics

\n\n\n

Python objects, Lists

"}︡ ︠8851009d-4e52-40ad-9ec6-6b894538adaa︠ #assign an empty list alist = list() blist = [] #append concatenates its argument to the list, extend is an item-wise append alist.append("a") blist.extend([1, 2, 3]) blist ︡7e04cc5a-5ce0-4f49-8bd8-f2453a5eaa6d︡{"stdout": "[1, 2, 3]"}︡ ︠556e934e-f3f9-4c17-b30e-ba32e7eac358︠ #list indices start at 0 blist[0] ︡e6166124-fb69-4c95-adb3-1a507b2e4e1e︡{"stdout": "1"}︡ ︠c91653f8-65f1-49a0-a089-c6f470ab39d9︠ #lists can contain objects of any type including other lists alist.append(10) alist.append(["a string", 1e6, True]) alist ︡ef22d454-84be-4e5b-a59f-8856ffc10f01︡{"stdout": "['a', 10, ['a string', 1.00000000000000e6, True]]"}︡ ︠da814f69-23e6-4867-96c0-1c24163a42fb︠ #contigious sub-lists can be extracted by slicing some_numbers = range(1000) subset = some_numbers[5:10] subset ︡d30bedfd-2b8b-4e26-b96b-80465fd6df7b︡{"stdout": "[5, 6, 7, 8, 9]"}︡ ︠d86bd757-a155-46b3-a38b-ceab6c0775d4︠ #assign an empty dictionary to adict adict = {} #the string "case1" (the key) now maps to a list (the value) adict['case1'] = ["John", "Smith", "HIV-"] adict ︡f1d1a996-2c01-4c59-83fd-f3d1539e3214︡{"stdout": "{'case1': ['John', 'Smith', 'HIV-']}"}︡ ︠267443a5-301a-4178-893e-6d3e51ca8375︠ #append a string to a hashed list adict['case1'].append('new data') adict ︡a24524c0-0690-49f6-8b6a-125d26d61809︡{"stdout": "{'case1': ['John', 'Smith', 'HIV-', 'new data']}"}︡ ︠e7afe2ab-153b-416d-82fa-966518ee11c5︠ #any immutable object can be a dictionary key (i.e. lists can not be keys) adict[[2, "case2"]] = ["Jill"] ︡cca01cf2-6fe0-4324-b473-1b51628e8973︡{"stderr": "Traceback (most recent call last):\n File \"\", line 1, in \n File \"_sage_input_32.py\", line 10, in \n exec compile(u'open(\"___code___.py\",\"w\").write(\"# -*- coding: utf-8 -*-\\\\n\" + _support_.preparse_worksheet_cell(base64.b64decode(\"I2FueSBpbW11dGFibGUgb2JqZWN0IGNhbiBiZSBhIGRpY3Rpb25hcnkga2V5IChpLmUuIGxpc3RzIGNhbiBub3QgYmUga2V5cykKCmFkaWN0W1syLCAiY2FzZTIiXV0gPSBbIkppbGwiXQ==\"),globals())+\"\\\\n\"); execfile(os.path.abspath(\"___code___.py\"))' + '\\n', '', 'single')\n File \"\", line 1, in \n \n File \"/tmp/tmp3KZArv/___code___.py\", line 4, in \n exec compile(u'adict[[_sage_const_2 , \"case2\"]] = [\"Jill\"]' + '\\n', '', 'single')\n File \"\", line 1, in \n \nTypeError: unhashable type: 'list'"}︡ ︠d2280c58-9cd7-4641-b676-95b2f34951f4︠ #tuples are immutable lists and can function as keys adict[(2, "case2")] = ["Jill"] adict ︡ef25cc48-9cbf-45bf-b97d-f3ff1ec19255︡{"stdout": "{'case1': ['John', 'Smith', 'HIV-', 'new data'], (2, 'case2'): ['Jill']}"}︡ ︠f7f98a70-330f-4450-b7ae-5a0cb14c6bb3i︠ %html

Python basics, loops and list comprehensions

  • Any itterable object can be looped (lists, tupples, dictionary, arrays, etc...)
︡f3c3bf47-974e-446f-85f7-1e68ea03f265︡{"html": "
\n

Python basics, loops and list comprehensions

\n
    \n
  • Any itterable object can be looped (lists, tupples, dictionary, arrays, etc...)
  • \n
\n
"}︡ ︠f5f6efb7-87e7-4309-aeaa-3c18187c6d01︠ iter = [1,2,3,4,5,6] for x in iter: print x**2 ︡c60c61d4-7d86-4c54-925b-8784074d6de7︡{"stdout": "1\n4\n9\n16\n25\n36"}︡ ︠cc0eb72e-3d46-4fec-b1f0-4741f31c3b9f︠ #for loops can assign variables from tuples in the loop definition #for example, dict.items() returns a list of key-value tuples which are unpacked and assigned to the names k and v respectively for k, v in adict.items(): print k, v[0] ︡8f3d3104-f41a-4ced-992c-0deedf5636a5︡{"stdout": "case1 John\n(2, 'case2') Jill"}︡ ︠ea2d6d11-2752-44ff-a999-fe5126151b05i︠ %html
  • while loops constantly executes while <expression> evaluates to true
  • while <expression>:
  • everything in python has a truth value and therefore any thing function as <expression>
︡351d2a8e-8e06-4f25-a3a1-9f9241f15812︡{"html": "
\n
    \n
  • while loops constantly executes while <expression> evaluates to true
  • \n
  • while <expression>:
  • \n
  • everything in python has a truth value and therefore any thing function as <expression>
  • \n
\n
"}︡ ︠76308385-b468-4ccf-a0f9-11bb013977bf︠ #list comprehensions are very ways to do stuff to lists [float(x) for x in iter] ︡91ba01c0-7a53-44da-9650-3a2e891d5fb1︡{"stdout": "[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]"}︡ ︠657c53bc-fb62-45a8-a758-0aeadc9a86ed︠ #list comprehensions can accept conditionals also [float(x) for x in iter if x > 3] ︡f71cbc0f-56f9-4339-99f5-d512452fad0c︡{"stdout": "[4.0, 5.0, 6.0]"}︡ ︠d12dca7b-ac8f-45c9-8037-6133e1a3c979i︠ %html

The scipy ODE solver 

  • First, we need to import some external libraries into the global namespace
︡86594ebd-3475-4654-9c9b-927eaa224c00︡{"html": "

The scipy ODE solver 

\n
    \n
  • First, we need to import some external libraries into the global namespace
  • \n
"}︡ ︠fb3ffa98-acbc-49e0-a9a2-48109aed4c1b︠ import scipy.integrate as slv import numpy as np import pylab as pl ︡21dfee9a-82cb-464a-a419-d83a2e578055︡︡ ︠5778cfb1-8448-4b20-94e1-2392d419f893︠ slv.odeint? ︡394c562e-f1a9-440a-a1d0-c595a95f5dc9︡{"html": "\n\n
\n \n

File: /home/ethan/software/sage-4.6.2-linux-32bit-ubuntu_10.04_lts-i686-Linux-i686-Linux/local/lib/python2.6/site-packages/scipy/integrate/odepack.py

\n

Type: <type ‘function’>

\n

Definition: slv.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)

\n

Docstring:

\n
\n

Integrate a system of ordinary differential equations.

\n

Solve a system of ordinary differential equations using lsoda from the\nFORTRAN library odepack.

\n

Solves the initial value problem for stiff or non-stiff systems\nof first order ode-s:

\n
dy/dt = func(y,t0,...)\n
\n
\n

where y can be a vector.

\n
\n
func : callable(y, t0, ...)
\n
Computes the derivative of y at t0.
\n
y0 : array
\n
Initial condition on y (can be a vector).
\n
t : array
\n
A sequence of time points for which to solve for y. The initial\nvalue point should be the first element of this sequence.
\n
args : tuple
\n
Extra arguments to pass to function.
\n
Dfun : callable(y, t0, ...)
\n
Gradient (Jacobian) of func.
\n
col_deriv : boolean
\n
True if Dfun defines derivatives down columns (faster),\notherwise Dfun should define derivatives across rows.
\n
full_output : boolean
\n
True if to return a dictionary of optional outputs as the second output
\n
printmessg : boolean
\n
Whether to print the convergence message
\n
\n
\n
y : array, shape (len(y0), len(t))
\n
Array containing the value of y for each desired time in t,\nwith the initial value y0 in the first row.
\n
infodict : dict, only returned if full_output == True
\n

Dictionary containing additional output information

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
keymeaning
‘hu’vector of step sizes successfully used for each time step.
‘tcur’vector with the value of t reached for each time step.\n(will always be at least as large as the input times).
‘tolsf’vector of tolerance scale factors, greater than 1.0,\ncomputed when a request for too much accuracy was detected.
‘tsw’value of t at the time of the last method switch\n(given for each time step)
‘nst’cumulative number of time steps
‘nfe’cumulative number of function evaluations for each time step
‘nje’cumulative number of jacobian evaluations for each time step
‘nqu’a vector of method orders for each successful step.
‘imxer’index of the component of largest magnitude in the\nweighted local error vector (e / ewt) on an error return, -1\notherwise.
‘lenrw’the length of the double work array required.
‘leniw’the length of integer work array required.
‘mused’a vector of method indicators for each successful time step:\n1: adams (nonstiff), 2: bdf (stiff)
\n
\n
\n
\n
ml, mu : integer
\n
If either of these are not-None or non-negative, then the\nJacobian is assumed to be banded. These give the number of\nlower and upper non-zero diagonals in this banded matrix.\nFor the banded case, Dfun should return a matrix whose\ncolumns contain the non-zero bands (starting with the\nlowest diagonal). Thus, the return matrix from Dfun should\nhave shape len(y0) * (ml + mu + 1) when ml >=0 or mu >=0
\n
rtol, atol : float
\n
The input parameters rtol and atol determine the error\ncontrol performed by the solver. The solver will control the\nvector, e, of estimated local errors in y, according to an\ninequality of the form max-norm of (e / ewt) <= 1,\nwhere ewt is a vector of positive error weights computed as:\newt = rtol * abs(y) + atol\nrtol and atol can be either vectors the same length as y or scalars.\nDefaults to 1.49012e-8.
\n
tcrit : array
\n
Vector of critical points (e.g. singularities) where integration\ncare should be taken.
\n
h0 : float, (0: solver-determined)
\n
The step size to be attempted on the first step.
\n
hmax : float, (0: solver-determined)
\n
The maximum absolute step size allowed.
\n
hmin : float, (0: solver-determined)
\n
The minimum absolute step size allowed.
\n
ixpr : boolean
\n
Whether to generate extra printing at method switches.
\n
mxstep : integer, (0: solver-determined)
\n
Maximum number of (internally defined) steps allowed for each\nintegration point in t.
\n
mxhnil : integer, (0: solver-determined)
\n
Maximum number of messages printed.
\n
mxordn : integer, (0: solver-determined)
\n
Maximum order to be allowed for the nonstiff (Adams) method.
\n
mxords : integer, (0: solver-determined)
\n
Maximum order to be allowed for the stiff (BDF) method.
\n
\n

ode : a more object-oriented integrator based on VODE\nquad : for finding the area under a curve

\n
\n\n\n
\n"}︡ ︠7c2ae088-6fbb-4a6d-85f3-f9dd84f2d36f︠ #first task is to define a function that returns dY/dt (a vector) given a vector of parameters and a state vector at time t (useful for time variable parameters, can be otherwise ignored) #parameters beta = 0.05 #per-act probability of transmission c = 10 #contact rate d = 0.01 #death rate def odefunc(Y, t=0): sus, inf = Y #unpack and name the state variables for clarity N = np.sum(Y) incidence = sus * c * beta * inf/float(N) death = inf * d return [-incidence, incidence - death] #test the ode function odefunc([10000, 10]) ︡003c6bbc-b0e8-4eaf-9da6-1093150ac9f5︡{"stdout": "[-4.99500499500499, 4.89500499500499]"}︡ ︠ebb0a849-a06f-4bcf-b01d-6c0aa2da4c07︠ #the solver needs the initial conditions and a sequence of times (the solver is adaptive so I'm not sure why the sequence is needed) start, stop = 0, 120 span = stop - start out = slv.odeint(odefunc, y0=[10000, 1], t=np.linspace(start, stop, span*100), full_output=True) ︡21e30abf-ebe1-442c-a454-5e193f6dd1f6︡︡ ︠c942bffc-f5f2-4839-8d49-a4430f96eb21︠ #when in doubt print the object type, multiple returns will almost print type(out) ︡b17f9947-7d5d-4b95-91be-46bd7495f4d9︡{"stdout": ""}︡ ︠51f4f01d-9ed7-4275-b9ea-454f5a8dc3af︠ #python allows multiple returns, returns are always placed in a tuple # in this case, the first element is the state of the system states = out[0] states ︡40c1a14c-79db-40a1-a863-ea1f33327fd3︡{"stdout": "array([[ 1.00000000e+04, 1.00000000e+00],\n [ 9.99999499e+03, 1.00491194e+00],\n [ 9.99998995e+03, 1.00984801e+00],\n ..., \n [ -8.57803540e-10, 3.63588769e+03],\n [ -8.54621682e-10, 3.63552409e+03],\n [ -8.51391528e-10, 3.63516053e+03]])"}︡ ︠f781522c-f355-4d1f-b46c-f3214fde60a7︠ # the second element is a dictionary with additional information on the solution infodic = out[1] #the keys to a dictionary with other useful information on the information for k, v in infodic.items(): print k, v ︡6e4903a2-5c8b-403d-923b-0e8d7faccb69︡{"stdout": "nfe [ 7 9 11 ..., 477 477 477]\nnje [0 0 0 ..., 0 0 0]\ntolsf [ 0. 0. 0. ..., 0. 0. 0.]\nnqu [2 2 2 ..., 3 3 3]\nlenrw 52\ntcur [ 1.02343971e-02 2.04663527e-02 3.06983082e-02 ..., 1.21510430e+02\n 1.21510430e+02 1.21510430e+02]\nhu [ 0.01023196 0.01023196 0.01023196 ..., 1.85333389 1.85333389\n 1.85333389]\nimxer -1\nleniw 22\ntsw [ 0. 0. 0. ..., 0. 0. 0.]\nmessage Integration successful.\nnst [ 3 4 5 ..., 230 230 230]\nmused [1 1 1 ..., 1 1 1]"}︡ ︠2d2c2e2c-cf92-4f03-9df0-43e5b29a8317i︠ %html

Plotting the time trajectory of the system with pylab

︡4ec7adbc-7b92-4d22-a1c3-190a0f11c207︡{"html": "

Plotting the time trajectory of the system with pylab

"}︡ ︠7eb287de-f600-4866-8232-ebacc355fed3︠ #first we want to extract the solution times and the state vector at those times #the solver returns a numpy array, which is like an unmodifiable list that behaves more 'mathy' than a regular list. #the solution is a 2D array (arrays can have any integer of dimensions), columns of 2D arrays can be selected thus-wise states[:,0] ︡cc36d1db-f766-4f70-9591-9af9792b5117︡{"stdout": "array([ 1.00000000e+04, 9.99999499e+03, 9.99998995e+03, ...,\n -8.57803540e-10, -8.54621682e-10, -8.51391528e-10])"}︡ ︠db5827bc-d672-42e5-834f-6e93f8447155︠ pl.close() pl.plot(infodic['tcur'], states[:,0][1:], 'b-', label='susceptibles') pl.show() pl.savefig('p1') ︡ad318298-532e-4ebe-868c-bac0e8094c0a︡︡ ︠bc85edc4-60ac-4251-9027-f8912300d2da︠ #additional aspects can be added to the plot by calling other pylab functions pl.plot(infodic['tcur'], states[:,1][1:], 'r-', label='infecteds') pl.legend() pl.show() pl.savefig('p1') ︡75f47762-1447-4db3-bad2-24df6ea048a5︡︡