<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Computational Legal Studies™ &#187; jzelner</title>
	<atom:link href="http://computationallegalstudies.com/author/jzelner/feed/" rel="self" type="application/rss+xml" />
	<link>http://computationallegalstudies.com</link>
	<description></description>
	<lastBuildDate>Sat, 19 May 2012 21:05:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Programming Dynamic Models in Python-Part 3: Outbreak on a Network</title>
		<link>http://computationallegalstudies.com/2009/11/15/programming-dynamic-models-in-python-3-outbreak-on-a-network/</link>
		<comments>http://computationallegalstudies.com/2009/11/15/programming-dynamic-models-in-python-3-outbreak-on-a-network/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 20:37:36 +0000</pubDate>
		<dc:creator>jzelner</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[agent based models]]></category>
		<category><![CDATA[network analysis]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[social epidemiology]]></category>

		<guid isPermaLink="false">http://computationallegalstudies.com/?p=2697</guid>
		<description><![CDATA[In this post, we will continue building on the basic models we discussed in the first and second tutorials. If you haven&#8217;t had a chance to take a look at them yet, definitely go back and at least skim them, &#8230; <a href="http://computationallegalstudies.com/2009/11/15/programming-dynamic-models-in-python-3-outbreak-on-a-network/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">In this post, we will continue building on the basic models we discussed in the <a href="http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/" target="_self"><strong>first</strong></a> and <a href="http://computationallegalstudies.com/2009/10/21/programming-dynamic-models-in-python-coding-efficient-dynamic-models/" target="_self"><strong>second</strong></a> tutorials. If you haven&#8217;t had a chance to take a look at them yet, definitely go back and at least skim them, since the ideas and code there form the backbone of what we&#8217;ll be doing here.</p>
<p style="text-align: justify;">In this tutorial, we will build a model that can simulate outbreaks of disease on a <a href="http://en.wikipedia.org/wiki/Small-world_network" target="_blank"><strong>small-world network</strong></a> (although the code can support arbitrary networks).  This tutorial represents a shift away from both: <strong> </strong></p>
<p style="text-align: justify;"><strong>a)</strong> the mass-action mixing of the first two and and <strong> </strong></p>
<p style="text-align: justify;"><strong>b)</strong> the assumption of social homogeneity across individuals that allowed us to take some shortcuts to simplify model code and speed execution. Put another way, we&#8217;re moving more in the direction of individual-based modeling.</p>
<p style="text-align: justify;">When we&#8217;re done, your model should be producing plots that look like this:</p>
<div id="attachment_2716" class="wp-caption aligncenter" style="width: 310px"><img class="size-medium wp-image-2716" title="netplotoutbreak" src="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/11/netplotoutbreak1-300x300.png" alt="Outbreak on a small-world network" width="300" height="300" /><p class="wp-caption-text">Outbreak on a small-world network</p></div>
<p>Red nodes are individuals who have been infected before the end of the run, blue nodes are never-infected individuals and green ones are the index cases who are infectious at the beginning of the run.</p>
<p>And your model will be putting out interesting and unpredictable results such as these:</p>
<div id="attachment_2713" class="wp-caption aligncenter" style="width: 310px"><img class="size-medium wp-image-2713" title="outbreakplot" src="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/11/outbreakplot-300x151.png" alt="Time vs. # of cases" width="300" height="151" /><p class="wp-caption-text">Time vs. # of cases</p></div>
<p>In order to do this one, though, you&#8217;re going to <em><span style="color: #ff0000;"><strong>need</strong></span></em><span style="color: #ff0000;"> </span>to download and install have <a href="http://igraph.sourceforge.net/download.html" target="_blank"><strong>igraph</strong></a> for Python on your system.</p>
<h2>Individual-Based Networks</h2>
<p style="text-align: justify;">
<p style="text-align: justify;">It is important to make the subtle distinction between <em>individual</em> and <a href="http://en.wikipedia.org/wiki/Agent-based_model" target="_blank"><em><strong>agent based models</strong></em></a> very clear here. Although the terms  are often used interchangeably, referring to our nodes, who have no agency, <em>per se</em>, but are instead fairly static receivers and diffusers of infection, as agents, seems like overreaching. Were they to exhibit some kind of adaptive behavior, i.e., avoiding infectious agents or removing themselves from the population during the infective period, they then become more agent-like.</p>
<p style="text-align: justify;">This is not to under- or over-emphasize the importance or utility of either approach, but just to keep the distinction in mind to avoid the &#8220;when all you have is a hammer, everything looks like a nail&#8221; problem.</p>
<p style="text-align: justify;">In short, <a href="http://www.pnas.org/content/99/suppl.3/7187.full.pdf" target="_blank"><strong>adaptive agents are great</strong></a>, but they&#8217;re overkill if you don&#8217;t need them for your specific problem.</p>
<h2>Small World Networks</h2>
<p style="text-align: justify;">The guiding idea behind small-world networks is that they capture some of the structure seen in more realistic contact networks: most contacts are regular in the sense that they are fairly predicable, but there are some contacts that span tightly <a href="http://en.wikipedia.org/wiki/Clustering_coefficient" target="_blank"><strong>clustered</strong></a> social groups and bring them together.</p>
<p style="text-align: justify;">In the basic small-world model, an individual is connected to some (small, typically &lt;=8) number of his or her immediate neighbors. Some fraction of these network connections are then randomly re-wired, so that some individuals who were previously distant in network terms &#8211; i.e., connected by a large number of jumps &#8211; are now adjacent to each other. This also has the effect of shortening the distance between their neighbors and individuals on the other side of the graph. Another way of putting this is that we have shortened the <a href="http://en.wikipedia.org/wiki/Average_path_length"><strong>average path length</strong></a> and increased the average reachability of all nodes.</p>
<p style="text-align: justify;">These random connections are sometimes referred to as &#8220;weak ties&#8221;, as there are fewer of these ties that bridge clusters than there are within clusters. When these networks are considered from a sociological perspective, we often expect to find that the relationship represented by a weak tie is one in which the actors on either end have less in common with each other than they do with their &#8216;closer&#8217; network neighbors.</p>
<p style="text-align: justify;"><a href="http://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model"><strong>Random networks</strong></a> also have the property of having short average path lengths, but they lack the clustering that gives the small-world model that pleasant smell of quasi-realism that makes them an interesting but largely tractable, testing ground for theories about the impact of social structure on dynamic processes.</p>
<h2>Installation and Implementation Issues</h2>
<p style="text-align: justify;">If you have all the pre-requisites installed on your system, you should be able to just copy and paste this code into a new file and run it with your friendly, local Python interpreter. When you run the model, you should first see a plot of the network, and when you close this, you should see a plot of the number of infections as a function of time shortly thereafter.</p>
<p style="text-align: justify;">Aside from the addition of the network, the major conceptual difference is that the model operates on discrete individuals instead of a homogeneous population of agents. In this case, the only heterogeneity is in the number and identity of each individual&#8217;s contacts, but there&#8217;s no reason we can&#8217;t (and many do) incorporate more heterogeneity (biological, etc.) into a very similar model framework.</p>
<p style="text-align: justify;">With Python, this change in orientation to homogeneous nodes to discrete individuals seems almost trivial, but in other languages it can be somewhat painful. For instance, in C/++, a similar implementation would involve defining a <a href="http://en.wikipedia.org/wiki/Struct_%28C_programming_language%29" target="_blank"><strong>struct</strong></a> with fields for recovery time and individual ID, and defining a custom comparison operator for these structs. Although this is admittedly not a super-high bar to pass, it adds enough complexity that it can scare off novices and frustrate more experienced modelers.</p>
<p style="text-align: justify;">Perhaps more importantly, it often has the effect of convincing programmers that a more heavily object-oriented approach is the way to go, so that each individual is a discrete object. When our individuals are as inert as they are in this model, this ends up being a waste of resources and makes for significantly more cluttered code. The end result can often be a model written in a language that is ostensibly faster than Python, such as C++ or Java, that runs slower than a saner (and more readable) Python implementation.</p>
<p style="text-align: justify;">For those of you who are playing along at home, here are some things to think about and try with this model:</p>
<ol style="text-align: justify;">
<li>Change the kind of network topology the model uses (you can find all of the different networks available in igraph <a href="http://igraph.sourceforge.net/doc/python/igraph.GraphBase-class.html" target="_blank"><strong>here</strong></a>).</li>
<li>Incorporate another level of agent heterogeneity: Allow agents to have differing levels of infectivity (Easier); Give agents different recovery time distributions (Harder, but not super difficult).</li>
<li>Make two network models &#8211; you can think of them as separate towns &#8211; and allow them to weakly influence each other&#8217;s outbreaks. (Try to use the object-oriented framework here with minimal changes to the basic model.)</li>
</ol>
<p style="text-align: justify;">That&#8217;s it for tutorial #3, (other than reviewing the comment code which is below) but definitely check back for more on network models!</p>
<p style="text-align: justify;">In future posts, we&#8217;ll be thinking about more dynamic networks (i.e., ones where the links can change over time), agents with a little more agency, and tools for generating dynamic visualizations (i.e., movies!) of stochastic processes on networks.</p>
<p style="text-align: justify;">That really covers the bulk of the major conceptual issues. Now let&#8217;s work through the implementation.</p>
<h3 style="font-size: 1.17em; text-align: center;"><strong><span style="color: #0000ff;">Click Below to Review the Implementation and Commented Code!</span></strong></h3>
<p style="text-align: center;"><strong><span style="color: #0000ff;"><span id="more-2697"></span><br />
</span></strong></p>
<p style="text-align: center;"><span style="font-weight: bold;">Okay, thanks for clicking through&#8230; now follow along with the comments in the code below:</span><br />
<script src="http://gist.github.com/234127.js"></script></p>
<div style="text-align: center;"><strong><br />
</strong></div>
<p style="text-align: justify;">
<p style="text-align: justify;">
]]></content:encoded>
			<wfw:commentRss>http://computationallegalstudies.com/2009/11/15/programming-dynamic-models-in-python-3-outbreak-on-a-network/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Programming Dynamic Models in Python: Coding Efficient Dynamic Models</title>
		<link>http://computationallegalstudies.com/2009/10/21/programming-dynamic-models-in-python-coding-efficient-dynamic-models/</link>
		<comments>http://computationallegalstudies.com/2009/10/21/programming-dynamic-models-in-python-coding-efficient-dynamic-models/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 04:02:17 +0000</pubDate>
		<dc:creator>jzelner</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[computational social science]]></category>
		<category><![CDATA[Dynamic Models]]></category>
		<category><![CDATA[network analysis]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[social epidemiology]]></category>

		<guid isPermaLink="false">http://computationallegalstudies.com/?p=2260</guid>
		<description><![CDATA[In the next few tutorials, we&#8217;re going to transition to exploring how to model dynamics on a network. The first tutorial was a bit of a blockbuster length-wise because there was a lot of ground to cover to get the &#8230; <a href="http://computationallegalstudies.com/2009/10/21/programming-dynamic-models-in-python-coding-efficient-dynamic-models/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;"><a href="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/10/python1.jpg"><img class="alignleft size-full wp-image-2374" title="python" src="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/10/python1.jpg" alt="python" width="166" height="154" /></a>In the next few tutorials, we&#8217;re going to transition to exploring how to model dynamics on a network.</p>
<p style="text-align: justify;">The <a href="http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/"><strong>first tutorial</strong></a> was a bit of a blockbuster length-wise because there was a lot of ground to cover to get the basic model up and running. Moving forward, we&#8217;ll be able to go a bit more incrementally, adding elements to the basic model as we go. If you don&#8217;t feel comfortable with the original, go back and take a look at it and make sure that it makes sense to you before moving on.</p>
<p style="text-align: justify;">We&#8217;re first going to deal with some of the efficiency issues in the first model. After this, we&#8217;ll make some basic changes to the architecture of the SIR program that makes it more amenable to contact patterns on a social network.</p>
<p style="text-align: left;">Finally, we&#8217;ll show you how to how to take the output of your epidemic model and generate animations like this one:</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="324" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/OWw9GLgoBik&amp;hl=en&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="400" height="324" src="http://www.youtube.com/v/OWw9GLgoBik&amp;hl=en&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p style="text-align: justify;"><span style="color: #0000ff;"><strong>Blue nodes</strong></span> are exposed but uninfected, <span style="color: #ff0000;"><strong>red nodes</strong></span> are infectious, and <span style="color: #ffff00;"><strong><span style="color: #ffcc00;">yellow ones</span></strong></span><span style="color: #ffcc00;"> </span>have recovered.</p>
<p style="text-align: justify;">The movie is a bit of a carrot to get you through the less flashy, but, I promise, important and actually interesting nuts and bolts of putting these kinds of models together.</p>
<p style="text-align: justify;">This tutorial is going to cover the last two big things that we need to tackle before we get to the model of an outbreak on a network. So, here we go!</p>
<h2 style="text-align: justify;">New Concepts</h2>
<h4 style="text-align: justify;">1. Arbitrarily Distributed Infectious Periods</h4>
<p style="text-align: justify;">First, we&#8217;re going to deal with the duration of the infectious period. The assumption of an exponentially distributed infectious period is unnecessarily restrictive for a general model of diffusion, and the way the original code goes about recovering individuals &#8211; drawing a random number on every step for every infectious individual &#8211; should strike you as both inelegant and computationally inefficient, particularly when the rate of recovery is slow and there are many infectious individuals.</p>
<p style="text-align: justify;">In order to deal with this, we&#8217;re going to introduce two new tools. The first is the scipy.stats toolkit and the second is a neat (and very easy to use) data structure called a <a href="http://en.wikipedia.org/wiki/Heap_%28data_structure%29"><strong>heap</strong></a>.</p>
<p style="text-align: justify;">A heap is in very many ways what it sounds like: imagine a pile of trash in a landfill; the tires and rusting washing machines are on the bottom, while the pop cans and grocery store receipts are closer to the top.</p>
<p style="text-align: justify;">As a programming tool, a heap is useful because it always keeps the smallest (or largest, depending on your preference) item at the top of the list.  It also allows for <a href="http://en.wikipedia.org/wiki/Linear_time"><strong>linear-time</strong></a> insertion and removal of objects. This means that the time it takes to execute an action grows proportionally to the size of the list, so if it has N items, it takes N*C steps (where C is a constant) to process the list, and if it has 2*N items, it takes 2*N*C steps. Other ways of sorting could take N^2 or worse steps to do the same.</p>
<p style="text-align: justify;">In our outbreak model, the top item on the heap is always going to be the time at which the next individual recovers. By doing this, we can avoid the loop in the first tutorial (and replicated in one implementation here) that checks whether each infectious individual is going to recover on each step.</p>
<p style="text-align: justify;">Looping over everyone is the most intuitive way to check if they&#8217;re going to recover, but it&#8217;s very inefficient, especially when infectious periods are long and the population is large. It&#8217;s also problematic from a theoretical perspective, because it chains us to exponentially distributed recovery periods.</p>
<p style="text-align: justify;">Exponentially distributed infectious periods make analytic sense for a deterministic model, but your disease or *insert diffusible here* may have a constant or normally distributed &#8216;infectious&#8217; period.</p>
<p style="text-align: justify;">By using a heap-based implementation, as you will see, we can use arbitrary recovery periods, and Python&#8217;s implementation of the heap is very straightforward &#8211; just a small twist on the usual list using the <a href="http://docs.python.org/library/heapq.html"><strong>heapq</strong></a> module.</p>
<h4 style="text-align: justify;">2. Object Oriented Programming</h4>
<p style="text-align: justify;">One of Python&#8217;s strengths is that it supports a style of programming that mixes the best of <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a> (OOP) and procedural or <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative </a>programming.</p>
<p style="text-align: justify;">We won&#8217;t go too deep into the details of OOP here, but the real strength of OOP implementations are that they allow code to be easily re-used in other programs (Python&#8217;s all-powerful &#8216;<a href="http://www.python.org/doc/2.5.2/ref/import.html">import</a>&#8216; statement really makes this true) and also forces some structure on what functions have access to what variables, etc.</p>
<p style="text-align: center;"><strong>Click Below to Review the Implementation and Commented Code! </strong></p>
<p style="text-align: center;"><span id="more-2260"></span></p>
<h2 style="text-align: justify;">Implementation</h2>
<p style="text-align: justify;">I&#8217;ll walk you through the steps of implementing and running the model below. If you aren&#8217;t familiar with how Python does OOP, go take a look <a href="http://docs.python.org/tutorial/classes.html#a-first-look-at-classes"><strong>here</strong></a> to get the basics down. Python OOP is very friendly, although its relative simplicity of implementation can be a double-edged sword when compared to more strongly-typed languages.</p>
<p style="text-align: justify;">For example, you could fill a list with a combination of the &#8216;simpleSIRModel&#8217; objects below, some integers, other Python lists, etc., but then you need to know what to do with every object as it comes off the list.</p>
<p style="text-align: justify;">This isn&#8217;t a very steep hill to climb, but it can be tricky if this is your first rodeo. By contrast, in Java, you would need to implement something known as a <a href="http://home.cogeco.ca/~ve3ll/jatutor5.htm"><strong>polymorphic array</strong></a> and then <a href="http://www.javabeginner.com/learn-java/java-object-typecasting"><strong>cast</strong></a> objects back to their type as you take them off of the list. That kind of type-safe implementation forces you to be aware of what objects are in what data structures, but you pay a penalty in terms of speed of coding and flexibility.</p>
<p style="text-align: justify;">By contrast, Python does some behind-the-scenes work to deal with lists of arbitrarily typed objects, but it makes your life a lot easier. I&#8217;ll discuss why you might want to do this after we walk through the code.</p>
<p style="text-align: justify;">For this one, you&#8217;re definitely going to need Python 2.4+ and a working install of relatively recent versions of Scipy and Numpy.</p>
<p style="text-align: justify;">(Mac users, just do yourself a favor and install the <a href="http://www.enthought.com/products/epd.php"><strong>Enthought Python Distribution</strong></a>.)</p>
<p style="text-align: justify;">
<p style="text-align: justify;"><script src="http://gist.github.com/214484.js"></script></p>
<p style="text-align: justify;">I think the justification for using a heap of recovery times is straightforward: it&#8217;s flexible, may be faster, and lets us use arbitrary recovery periods.  But why go all OOP?</p>
<p style="text-align: justify;">If you take a look back at the model in the first tutorial, it should become clear that the main way you&#8217;re going to re-use that code is by cutting and pasting.</p>
<p style="text-align: justify;">By contrast, this program can either be run using the Python interpreter (the code below &#8220;if __name__ == &#8216;__main__&#8217;:&#8221; only runs when it is used as a standalone program), or imported into another python script. We can then create multiple outbreak objects, <a href="http://en.wikipedia.org/wiki/Subclass_%28computer_science%29"><strong>subclass</strong></a> their methods, etc.</p>
<p style="text-align: justify;">For example, I have used the model in the code example below to simulate outbreaks in a collection of households that were all exposed to a gastrointestinal pathogen called <a href="http://en.wikipedia.org/wiki/Norovirus"><strong>norovirus</strong></a>. In order to do this, I import this code and create a new &#8216;communityOutbreak&#8217; object type that is filled with simpleSIRModel objects. When I call this object&#8217;s &#8216;run&#8217; method, it calls the run method of each simpleSIRModel object contained within and records the results.</p>
<p style="text-align: justify;">When we get to the networked outbreak model, I&#8217;ll show you another scenario where it can be helpful to import components from one model into another.</p>
<p style="text-align: justify;">Ok, some food for thought for those of you playing along at home:</p>
<ol>
<li>How could we better use objects here to use arbitrary recovery time distributions?</li>
<li>How could you make this even more flexible as a command-line program? Try to add command line arguments using either Python&#8217;s argv or <a href="http://docs.python.org/library/getopt.html"><strong>getopt</strong></a> tools.</li>
<li>Try to run this a multiple times and output averages of the runs over time to get a sense of the model&#8217;s asymptotic behavior.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://computationallegalstudies.com/2009/10/21/programming-dynamic-models-in-python-coding-efficient-dynamic-models/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Programming Dynamic Models in Python</title>
		<link>http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/</link>
		<comments>http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 18:07:28 +0000</pubDate>
		<dc:creator>jzelner</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[computational social science]]></category>
		<category><![CDATA[Dynamic Models]]></category>
		<category><![CDATA[network analysis]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[social epidemiology]]></category>

		<guid isPermaLink="false">http://computationallegalstudies.com/?p=2192</guid>
		<description><![CDATA[In this series of tutorials, we are going to focus on the theory and implementation of transmission models in some kind of population. In epidemiology, it is common to model the transmission of a pathogen from one person to another. &#8230; <a href="http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;"><a href="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/10/python.jpg"><img class="alignleft size-full wp-image-2238" title="python" src="http://ec2-107-21-222-181.compute-1.amazonaws.com/wp-content/uploads/2009/10/python.jpg" alt="python" width="166" height="154" /></a>In this series of tutorials, we are going to focus on the theory and implementation of transmission models in some kind of population.</p>
<p style="text-align: justify;">In <a href="http://en.wikipedia.org/wiki/Epidemiology"><strong>epidemiology</strong></a>, it is common to model the transmission of a <a href="http://en.wikipedia.org/wiki/Pathogen"><strong>pathogen</strong></a> from one person to another. In the social sciences and law, we may be interested in thinking about the way in which individuals influence each other&#8217;s opinions, ideology and actions.</p>
<p style="text-align: justify;">These two examples are different, but in many ways analogous: it is not difficult to imagine the influence that one individual has on another as being similar to the infectivity of a virus in the sense that both have the ability to change the state of an individual. One may go from being susceptible to being infected, or from unconvinced to convinced.</p>
<p style="text-align: justify;">Additionally, social networks have become an important area of study for epidemiological modelers. We can imagine that the nature of the network is different than the ones we think about in the social sciences: when studying outbreaks of a sexually transmitted disease, one doesn&#8217;t care all that much about the friendship networks of the people involved, while this would be very important for understanding the impact of social influence on depression and anxiety.</p>
<p style="text-align: justify;">As someone who spends a lot of time working in the space where epidemiology and sociology overlap, I end up thinking a lot about these models &#8211; and their potential application to new and different problems and am really excited to share them with a broader audience here. In this first tutorial, I&#8217;m going to introduce a simple<strong> </strong><a href="http://en.wikipedia.org/wiki/Epidemic_model"><strong>Susceptible-Infected-Recovered (SIR)</strong></a> model from infectious disease epidemiology and show a simple, Pythonic implementation of it. We&#8217;ll work through the process of writing and optimizing this kind of model in <a href="http://www.python.org/"><strong>Python</strong></a> and, in the final tutorials, will cover how to include a social network in the simulation model.</p>
<p style="text-align: justify;">
<p style="text-align: justify;">In order to use the example below, all you need to have installed is a current version of <a href="http://www.python.org/"><strong>Python</strong></a> (2.4+ is probably best) and the excellent <a href="http://www.python.org/"><strong>Python</strong></a> plotting package <a href="http://matplotlib.sourceforge.net/" target="_blank"><strong>Matplotlib</strong></a> in order to view output. If you don&#8217;t have <a href="http://matplotlib.sourceforge.net/" target="_blank"><strong>Matplotlib</strong></a> and don&#8217;t want to go and install it (although I guarantee you won&#8217;t regret it), just comment out import for Pylab and any lines related to plotting.</p>
<h2>Model Assumptions</h2>
<h4>1. State Space / Markov Model</h4>
<p style="text-align: justify;">Before getting into the mechanics of the model, let&#8217;s talk about the theory and assumptions behind the model as it is implemented here:</p>
<p style="text-align: justify;">The SIR model is an example of a &#8216;<a href="http://en.wikipedia.org/wiki/State_space"><strong>state space</strong></a>&#8216; model, and the version we&#8217;ll be talking about here is a <em>discrete time<strong>, </strong></em> <em><a href="http://en.wikipedia.org/wiki/Stochastic"><strong>stochastic</strong></a></em> implementation that has the <a href="http://en.wikipedia.org/wiki/Markov_property"><strong>Markov property</strong></a>, which is to say that its state at time <em>t+1</em> is only conditional on the parameters of the model and its state at time <em>t</em>.</p>
<div class="wp-caption aligncenter" style="width: 470px"><a href="http://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology"><img title="SIR Diagram" src="http://upload.wikimedia.org/wikipedia/en/8/8a/SIR.PNG" alt="A simple state-space diagram (courtesy of wikipedia)" width="460" height="69" /></a><p class="wp-caption-text">A simple state-space diagram (courtesy of Wikipedia)</p></div>
<p style="text-align: justify;">For the uninitiated, in a state-space model, we imagine that each individual in the system can only be in one state at a time and transitions from state to state as a function of the model parameters, i.e., the infectivity of the pathogen or idea and the rate of recovery from infection&#8230;and the other states of the system. In other words, the system has <em><a href="http://en.wikipedia.org/wiki/Endogeny"><strong>endogenous</strong></a></em><em> </em>dynamics. This is what makes it both interesting and in some ways difficult to work with.</p>
<p style="text-align: justify;">In the SIR model, we assume that each infectious individual infects each susceptible individual at rate <em>beta</em>. So, if <em>beta</em> = .5, there is a 50% chance that each susceptible individual will be infected by an exposure to an infectious individual. For this reason, as the number of infected individuals in the system grows, the rate at which the remaining susceptible individuals is infected also grows until the pool of susceptible individuals is depleted and the epidemic dies out.</p>
<p style="text-align: justify;">The other parameter we care about is <em>gamma</em>, or the rate of recovery. If <em>gamma</em> is also equal to .5, we assume that the average individual has a 50% chance of recovering on a given day, and the average duration of infectiousness will be 1/<em>gamma</em>, or 2 days.</p>
<p style="text-align: justify;">We refer to the ratio <em>beta/gamma</em> as the basic reproductive ratio, or Ro (&#8216;R naught&#8217;). When this number is less than one, we typically expect outbreaks to die out quickly. When this quantity is greater than one, we expect that the epidemic will grow and potentially saturate the whole population.</p>
<h4 style="text-align: justify;"><strong>2. Homogeneous Mixing:</strong></h4>
<p style="text-align: justify;"><strong> </strong>We&#8217;re assuming a world in which everyone has simultaneous contact with everyone else. In other words, we&#8217;re thinking of a totally connected social network. If you&#8217;re a regular reader of this blog, a social network enthusiast, or in some other way a thinking person, this assumption probably seems unreasonable. It turns out, however, that for many diseases, this assumption of homogeneous or &#8216;mass-action&#8217; mixing, which was actually originally borrowed from chemistry,  turns out to be a reasonable approximation.</p>
<p style="text-align: justify;">For instance, if we are trying to approximate the transmission dynamics of a very infectious pathogen like measles in a city or town, we can usually overlook social network effects at this scale and obtain a very good fit to the data. This is because even very weak contacts can transmit measles, so that friendships and other types of close contacts are not good predictors of risk. Instead, we we are better off looking at a higher level of organization &#8211; the pattern of connection between towns and cities to understand outbreaks. In a social context, something like panic may be thought of as being super-infectious (for a really interesting study about the potential relationship between social panic and flu dynamics, see <a href="http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1024270"><strong>this paper</strong></a> by Josh Epstein).</p>
<p style="text-align: justify;">This is, however, a generally problematic assumption for most problems of social influence, but an understanding of this most basic version of the model is necessary to move on to more complicated contact patterns.</p>
<h4 style="text-align: justify;"><strong>3. Exponentially distributed infectious periods</strong>:</h4>
<p style="text-align: justify;">In the most basic implementation of the SIR model, we assume that each infectious individual has some probability of recovering on every step. If our model steps forwards in days and individuals have a .5 probability of recovery on each day, we should expect that the time to recovery follows an exponential distribution. This means that most people will be pretty close to the mean, but some  will take a relatively long time to recover. This is accurate for a lot of cases, but definitely not for all. In some diseases, recovery times may be lognormal, power-law or bimodally disributed.  For social models, the notion of an &#8216;infectious period&#8217; may not make a tremendous amount of sense at all. But it allows for a very simple and transparent implementation, so we&#8217;ll use it here.</p>
<p style="text-align: justify;"><strong>CLICK THROUGH TO SEE THE IMPLEMENTATION and RELEVANT PYTHON CODE!</strong></p>
<p style="text-align: justify;"><span id="more-2192"></span></p>
<h2 style="text-align: justify;">Implementation</h2>
<p style="text-align: justify;">Ok, so now it&#8217;s time to move on to actually writing and running the model. If you have matplotlib installed, you should be able to just copy or save the code into a new file called &#8216;simpleSIR.py&#8217; and then run it from the command line using the command &#8216;python simpleSIR.py&#8217;.</p>
<p style="text-align: justify;">I&#8217;ll walk you through the substance of the model in the code:</p>
<p style="text-align: justify;"><script src="http://gist.github.com/205238.js"></script></p>
<p style="text-align: justify;">And that&#8217;s really it for a basic SIR model. This implementation leaves a lot to be desired, but that&#8217;s not really the point of this tutorial.</p>
<p style="text-align: justify;">In 36 lines of actual code (the vast majority of the program is comments), we implemented a stochastic, dynamic model and were able to take a look at the results.</p>
<p style="text-align: justify;">This is really a strength of using a Python based approach: it&#8217;s simple, easy to read (for those of you who are Matlab users, it should look pretty familiar), and quick to put together. The code in this file took me about 20 minutes to write.</p>
<p style="text-align: justify;">Your mileage may vary, but the point is that Python is great for getting up and going, prototyping your ideas and seeing what they look like. You can go very far with an all-Python model. If speed becomes a serious issue, you may think about blending in some <a href="http://en.wikipedia.org/wiki/C%2B%2B"><strong>C++</strong></a> for the really computationally intensive methods.</p>
<p style="text-align: justify;">For those of you playing along at home, before moving on to the next tutorials, spend some time with the following questions:</p>
<ol style="text-align: justify;">
<li>Would this model scale well? Where are there potential bottlenecks in the code?</li>
<li>What would an object-oriented implementation look like? Why would you want to try one?</li>
<li>How would you change the assumptions behind the model to look more like a more social scientific problem you care about?</li>
<li>What would have to (fundamentally) change in the code to be useful for thinking about outbreaks on a network?</li>
</ol>
<p style="text-align: justify;"><strong>Subsequent posts will cover the following topics (in roughly the following order):</strong></p>
<p style="text-align: justify;">#2) Tips and Tricks for writing more efficient model code.  (And why you should care!)</p>
<p style="text-align: justify;">#3) Writing Individual/Agent-Based models in Python</p>
<p style="text-align: justify;">#4) Implementing an SIR Model on a Network in Python</p>
<p style="text-align: justify;">#5) Animating networked outbreaks using <a href="http://csde.washington.edu/~skyebend/rsonia/rsoniaDemo/"><strong>rSonia</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://computationallegalstudies.com/2009/10/11/programming-dynamic-models-in-python/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using apc
Page Caching using apc
Database Caching using apc
Object Caching 411/420 objects using apc

Served from: computationallegalstudies.com @ 2012-05-22 09:34:58 -->
