︠9be24417-0a95-44e0-80af-1a794ed8c445i︠ %html
Resources for self-directed learning
Things you are going to need to get started
an editor that does python highlighting (gedit, emacs-linux, eclipse-linux,win,osx)
a python interpreter
python < 3.0 is syntatically different from python >= 3.0
you want python 2.6 or 2.7
I use ipython
Sage can also function as a python compiler, although the learning curve is a bit steep
There are hundreds of python libs for math/stats, the main ones you will need are scipy, numpy, and pylab
There are (probablly) binaries for windows
There are Debain packages for Debian-flavored linux distros
Python basics
python is an interpreted language (like R)
python is a combination of object-oriented (classes, inheritance) and functional paradigms
unless you are designing a whole API (you are not) its probably best to think of it as mostly functional environment (declaring variables in a global name space and writing methods to manipulate the state of those variables)
python should written in the most readable way possible; the standard style guide and docstring guides are widely available and great for insomnia.
Python objects, Lists
︡c57809a0-5056-470e-a272-2a28d52e85d7︡{"html": "Resources for self-directed learning
\n\n\n\nThings you are going to need to get started
\nan \teditor that does python highlighting (gedit, emacs-linux, \teclipse-linux,win,osx)
\na \tpython interpreter
\npython \t\t< 3.0 is syntatically different from python >= 3.0
\nyou \t\t\twant python 2.6 or 2.7
\nI \t\tuse ipython
\nSage \tcan also function as a python compiler, although the learning curve is a bit steep
\nThere \tare hundreds of python libs for math/stats, the main ones you will \tneed are scipy, numpy, and pylab
\nThere \t\tare (probablly) binaries for windows
\nThere \t\tare Debain packages for Debian-flavored linux distros
\nPython basics
\npython \tis an interpreted language (like R)
\npython \tis a combination of object-oriented (classes, inheritance) and \tfunctional paradigms
\nunless \tyou are designing a whole API (you are not) its probably best to \tthink of it as mostly functional environment (declaring variables in \ta global name space and writing methods to manipulate the state of \tthose variables)
\npython \tshould written in the most readable way possible; the standard style \tguide and docstring guides are widely available and great for insomnia.
\nPython 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 \"Python basics, loops and list comprehensions
Python basics, loops and list comprehensions
\nThe scipy ODE solver
The scipy ODE solver
\nFile: /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
\nType: <type ‘function’>
\nDefinition: 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)
\nDocstring:
\n\n\n\n\nIntegrate a system of ordinary differential equations.
\nSolve a system of ordinary differential equations using lsoda from the\nFORTRAN library odepack.
\nSolves the initial value problem for stiff or non-stiff systems\nof first order ode-s:
\n\n\ndy/dt = func(y,t0,...)\nwhere y can be a vector.
\n\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- \n
Dictionary containing additional output information
\n\n
\n\n \n\n\n \n \n\n\n key \nmeaning \n\n ‘hu’ \nvector of step sizes successfully used for each time step. \n\n ‘tcur’ \nvector with the value of t reached for each time step.\n(will always be at least as large as the input times). \n\n ‘tolsf’ \nvector of tolerance scale factors, greater than 1.0,\ncomputed when a request for too much accuracy was detected. \n\n ‘tsw’ \nvalue of t at the time of the last method switch\n(given for each time step) \n\n ‘nst’ \ncumulative number of time steps \n\n ‘nfe’ \ncumulative number of function evaluations for each time step \n\n ‘nje’ \ncumulative number of jacobian evaluations for each time step \n\n ‘nqu’ \na vector of method orders for each successful step. \n\n ‘imxer’ \nindex of the component of largest magnitude in the\nweighted local error vector (e / ewt) on an error return, -1\notherwise. \n\n ‘lenrw’ \nthe length of the double work array required. \n\n ‘leniw’ \nthe length of integer work array required. \n\n\n ‘mused’ \na vector of method indicators for each successful time step:\n1: adams (nonstiff), 2: bdf (stiff) \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.
\node : a more object-oriented integrator based on VODE\nquad : for finding the area under a curve
\n
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︡︡