<?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>code-spot &#187; Simulation</title>
	<atom:link href="http://code-spot.co.za/category/simulation/feed/" rel="self" type="application/rss+xml" />
	<link>http://code-spot.co.za</link>
	<description>a programming blog</description>
	<lastBuildDate>Wed, 25 Aug 2010 10:59:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A Simple Trick for Moving Objects in a Physics Simulation</title>
		<link>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-simple-trick-for-moving-objects-in-a-physics-simulation</link>
		<comments>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 19:24:24 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[damper]]></category>
		<category><![CDATA[force]]></category>
		<category><![CDATA[game programming]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[PID controller]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=1013</guid>
		<description><![CDATA[
(Original Image by Valerie Everett)
It is sometime necessary to move an object in a physics simulation to a specific point. On the one hand, it can be difficult to analyse the exact force you have to apply; on the other hand it might not look so good if you animate the object&#8217;s position directly.
A compromise [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/29/force-field-editor-v10/' rel='bookmark' title='Permanent Link: Force Field Editor v1.0'>Force Field Editor v1.0</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-1035" title="springs" src="http://code-spot.co.za/blog/wp-content/uploads/2010/07/springs2.png" alt="" width="488" height="257" /></p>
<p>(<a href="http://www.flickr.com/photos/valeriebb/248282508/sizes/o/">Original Image</a> by <a href="http://www.flickr.com/photos/valeriebb/">Valerie Everett</a>)</p>
<p>It is sometime necessary to move an object in a physics simulation to a specific point. On the one hand, it can be difficult to analyse the exact force you have to apply; on the other hand it might not look so good if you animate the object&#8217;s position directly.</p>
<p>A compromise that works well in many situations is to use a spring-damper system to move the object.</p>
<p>The trick is simple: we apply two forces—the one is proportional to the displacement; the other is proportional to the velocity. Tweaked correctly, they combine to give realistic movement to the desired point.</p>
<p><span id="more-1013"></span></p>
<p>The <a href="http://en.wikipedia.org/wiki/Hookes_law"><em>spring force</em></a> is proportional to the difference between the current position and the position where we want the object:</p>
<img src='http://s.wordpress.com/latex.php?latex=F_s%20%3D%20-k%28x%20-%20x_0%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_s = -k(x - x_0)' title='F_s = -k(x - x_0)' class='latex' />
<p>Here, <img src='http://s.wordpress.com/latex.php?latex=k&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k' title='k' class='latex' /> is a positive value called the <em>spring constant</em>.</p>
<p>As you can see, the force gets smaller as our object approaches the desired position, and becomes zero when it reaches that position. Unfortunately, in the absence of friction or drag, the <em>velocity</em> is not zero at this point, so the object overshoots the desired position, and moves past it. The force becomes bigger, but in the opposite direction. The object keeps on moving, slowing down, and finally starts moving in the opposite direction towards the desired position. This goes on indefinitely.</p>
<p>When there is friction or drag, we might be lucky enough for the system to slow down the object sufficiently so that its velocity becomes zero when the object reaches the desired position. This can be tricky to accomplish, though, and might impact the simulation environment in undesirable ways.</p>
<p>It is better to add a counteracting force explicitly. We add a <em>damper force</em> that is propostional to the velocity of the object, again opposite in direction. Here <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> is the <em>viscous damping coefficient</em>, also a positive number.</p>
<img src='http://s.wordpress.com/latex.php?latex=F_d%20%3D%20-cv&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_d = -cv' title='F_d = -cv' class='latex' />
<p>We then apply the sum of the forces to our object:</p>
<img src='http://s.wordpress.com/latex.php?latex=F_t%20%3D%20F_s%20%2B%20F_d&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_t = F_s + F_d' title='F_t = F_s + F_d' class='latex' />
<p>The trick is to choose <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> to get the behaviour we want.</p>
<p>Fortunately, this is easy. The following table summarizes how the damping constant affects behaviour. Here, <img src='http://s.wordpress.com/latex.php?latex=m&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m' title='m' class='latex' /> is the mass of the object.</p>
<table>
<tbody>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3D%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 0' title='c = 0' class='latex' /></td>
<td>The object oscillates.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=0%20%3C%20c%20%3C%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='0 &lt; c &lt; 2\sqrt{mk}' title='0 &lt; c &lt; 2\sqrt{mk}' class='latex' /></td>
<td>The object oscillates, but the oscillations die down.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3D%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 2\sqrt{mk}' title='c = 2\sqrt{mk}' class='latex' /></td>
<td>The object moves to the desired position without oscillating in minimum time.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3E%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c &gt; 2\sqrt{mk}' title='c &gt; 2\sqrt{mk}' class='latex' /></td>
<td>The object moves to the desired position without oscillating, and takes longer as c increases.</td>
</tr>
</tbody>
</table>
<p>If you want to see an explanation of how this works, see the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Damping">damping</a>.</p>
<p>By choosing <img src='http://s.wordpress.com/latex.php?latex=c%20%3D%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 2\sqrt{mk}' title='c = 2\sqrt{mk}' class='latex' />, we are left with only one parameter to tweak (the spring constant), with which we can adjust the time it will take for the object to reach the desired spot.</p>
<p>A simple implementation of this idea is given by the following function. The function should be called for every simulation frame, until we are satisfied that the object reached its spot:</p>
<pre>private void MoveTo(Rigidbody rigidbody, Vector3 newPosition,
      float springConstant)
{
  Vector3 desiredDisplacement = rigidbody.position - newPosition;
  Vector3 springForce = -springConstant * desiredDisplacement;

  float viscousDampingCoefficient
    = 2 * sqrt(rigidbody.mass * springConstant);

  Vector3 dampingForce
    = -viscousDampingCoefficient * rigidbody.velocity;

  Vector3 totalForce = springForce + dampingForce;
  rigidbody.AddForce(totalForce);
}</pre>
<p>This will work even when there is drag or friction, except that the object will move slower (in this case we can decrease the artificial damping, although it is a bit risky). When there is an external force applied to the object, the object will come to rest at some point away from the desired position. By increasing the spring constant, the distance between this point and the desired point can be made smaller. Thus, we can also use this scheme to maintain objects at a certain height, for example, which can give a rather realistic simulation of a hovercraft or even a drifting object.</p>
<p><strong>Update: </strong>This is an example of a <a href="http://en.wikipedia.org/wiki/PID_controller">PID controller</a> (proportional–integral–derivative controller), for which there is a C++ implementation in my <a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fcode-spot.co.za%2F2010%2F07%2F27%2Fa-simple-trick-for-moving-objects-in-a-physics-simulation%2F&amp;linkname=A%20Simple%20Trick%20for%20Moving%20Objects%20in%20a%20Physics%20Simulation"><img src="http://code-spot.co.za/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/29/force-field-editor-v10/' rel='bookmark' title='Permanent Link: Force Field Editor v1.0'>Force Field Editor v1.0</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cellular Automata for Simulation in Games</title>
		<link>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=cellular-automata-for-simulation-in-games</link>
		<comments>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 08:34:57 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[blending]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[Conway's game of life]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[diffusion]]></category>
		<category><![CDATA[discrete dynamics]]></category>
		<category><![CDATA[disease simulation]]></category>
		<category><![CDATA[fire simulation]]></category>
		<category><![CDATA[Game Maker]]></category>
		<category><![CDATA[grids]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[social dynamics]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=499</guid>
		<description><![CDATA[
A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately:
Conway’s Game of Life
Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of these depends [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline" title="header" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/header1.png" alt="header" width="500" height="371" /></p>
<p>A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately:</p>
<p><a href="http://psoup.math.wisc.edu/Life32.html">Conway’s Game of Life</a></p>
<p>Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of these depends on the current state as well as the states of neighbours. Usually, the state machines correspond to cells in a grid, and the neighbours of a cell are the cells connected to that cell. For a more detailed explanation, see <a href="http://en.wikipedia.org/wiki/Cellular_automata">the Wikipedia article</a>.</p>
<p>Even simple update rules can lead to interesting behaviour: patterns that cannot be predicted from the rules except by running them. With suitable rules, CA can simulate many systems:</p>
<ul>
<li>Natural phenomena: weather, fire, plant growth, migration patterns, spread of disease.</li>
<li>Socio-economic phenomena: urbanisation, segregation, construction and property development, traffic, spread of news.</li>
</ul>
<p><span id="more-499"></span></p>
<p>In games, these can be used as game elements (such as fire and disease), or they can also add some decorative life to a game (such as city development in a simulation game).</p>
<p>The great thing about CA systems is that they are not hard to implement, and they have intrinsic fun value (I mean here, for the programmer!).</p>
<p>Before we get into the details, let me add a small disclaimer here:</p>
<ul>
<li>This tutorial is not comprehensive. I only touch on a few ideas in a wide field. See some of the resources at the end for more information.</li>
<li>This tutorial is not representative. I merely chose topics I found interesting or thought would be useful for game developers.</li>
<li>I am not suggesting that using cellular automata is the best way to simulate any of the examples given here. For any problem, there might be solutions that are faster, easier to implement, or yield better results.</li>
</ul>
<h2>Implementation</h2>
<p>To implement a CA system, you need to do the following:</p>
<ul>
<li>Use a suitable system to store states, for example, a 2D array.</li>
<li>Decide on a suitable neighbourhood shape, and work out some preliminary rules. Decide how you will handle edges.</li>
<li>Implement a suitable way to describe your rules.</li>
<li>Implement an update function that hooks into the main game loop.</li>
<li>Implement a visualisation scheme (for example, drawing tiles depending on states in the array).</li>
</ul>
<p>Some details of these are described below.</p>
<h3>Grid</h3>
<p>A typical implementation uses two grids for storing states. One is the current world state; the other is the new world state. Once all cells have been updated for the current iteration, pointers to the arrays can be swapped. This way updating the cells one by one will not have an effect on other cells until the next iteration, and you do not have to create a new array in each iteration.</p>
<p>Using grids with square cells are the easiest to implement, but the concept is also applicable to other grids: hexagonal and triangular grids are also common, and even polar grids have been used to simulate spiral star systems.</p>
<p>It is also possible to use irregular systems, although the implementation then becomes a challenge. One example of an irregular system is a presentation based on a Poisson distribution of points. The trick here is to find an efficient way to locate neighbours. Fortunately, this problem has already been solved in creating the points (see the <a href="http://devmag.org.za/articles/55-POISSON-DISK-SAMPLING/">Poisson Sampling tutorial in Dev.Mag</a> and download code from <a href="http://www.luma.co.za/labs/tag/poisson-disk/">Luma Labs</a>). It is in fact done by using an invisible grid! Of course, visualising a state is also a bit more difficult.</p>
<h3>Neighbourhoods</h3>
<p>For 2D cellular automata, the most common neighbourhoods are the Von Neumann neighbourhood and the Moore neighbourhood, shown below (the blue cell’s neighbourhood is shown in red). Other neighbourhoods are also possible.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="vonneumann" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/vonneumann.png" alt="vonneumann" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="moore" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/moore.png" alt="moore" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="road" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/road.png" alt="road" width="88" height="88" /></td>
</tr>
<tr>
<td width="166" valign="top">Von Neumann neighbourhood</td>
<td width="166" valign="top">Moore neighbourhood</td>
<td width="166" valign="top">Extended Von Neumann neighbourhood</td>
</tr>
</tbody>
</table>
<p>The cell can be included in the neighbourhood or not. It is advisable to keep the neighbourhoods as small as possible: not only does the neighbourhood size impact performance, it also affects the number of rules to be specified and thus the tweaking complexity.</p>
<h3>Specifying Update Rules</h3>
<p>Specifying the rules concisely is the most challenging part of implementing CA. With very simple models, you might want to use a few if/else statements. This, however, makes it hard to modify (tweak or extend), and is therefore not suitable for more complicated systems.</p>
<p>It is best to implement rules as a table that can be indexed using the neighbourhood states.</p>
<p><strong>Table as an array.</strong> In this method, each row represents the combined state of the surrounding cells. The final entry in the row is the new state of the current cell. Each of the remaining columns represents a state. The entries in these columns represent the number of cells surrounding the current cell in that state.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top">Dry Bush</td>
<td width="125" valign="top">Burning Bush</td>
<td width="125" valign="top">Charcoal</td>
<td width="125" valign="top">New State</td>
</tr>
<tr>
<td width="125" valign="top">4</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
</tbody>
</table>
<p>A cell surrounded with three cells in the Dry Bush state and one cell in the Burning Bush state will go into the Burning Bush state.</p>
<p>This table can be quite large, so that you must take care to implement lookups efficiently. Keep the table sorted, and perform binary search to lookup entries. Below are some improvements on this scheme.</p>
<p><strong>Table as a tree.</strong> In the table above, it is easy to see that if there are three dry bush nodes, there are two possibilities for the other states (either 1 0, or 0 1). We can use this to implement a tree. Each level in the tree represents a state. A value in a node represents how many cells in the neighbourhood are in that state. A path from root to leaf fully describes the states of the entire neighbourhood. We do not add nodes for the last state, as it is uniquely determined by the other states.</p>
<p>Below is a tree corresponding to the piece of table above.</p>
<p>BB = Burning Bush</p>
<p>DB = Dry Bush</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="41" valign="top">root</td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 4</td>
<td width="50" valign="top"></td>
<td width="49" valign="top"></td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="42" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 3</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">|</td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 2</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 2</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">BB</td>
</tr>
</tbody>
</table>
<p>This is a more efficient implementation; unfortunately, it is also more complicated. It is inconvenient to specify the tree in a tree-friendly format (XML or s-expressions, for example). You still need to specify it in table format (space separated text file, for example) and build the tree from that.</p>
<p><strong>Implementation as a hash table.</strong> Here you use tuples of state counts as keys. For example, the third entry in the table above can be accessed with the tuple (3, 0, 1). If your implementation language does not support tuples, you might need to implement them yourself. Be sure to make them immutable!</p>
<p><strong>Implementation as an N-dimensional array.</strong> This is a very simple method, although it wastes a lot of memory. N is the number of states, and we use the state counts to index into the array. In our example, we will use a 3D array, so that the third element can be accessed using transition_array[3, 0, 1].</p>
<p>The method above can be used even when the implementation language does not provide N dimensional arrays. Simply use a 1D array, and interpret the state counts as the digits of a base-4 number. Thus, the third row will be located at 3*16 + 0*4 + 1*1 = 49.</p>
<p>Note that since the numbers are restricted by the requirement that they add to four, there will be unused array positions in both these last two methods. You can save memory by not using the last state to index (since it is uniquely determined by the other states). Thus, we can use a 2D array, and access the 3,0,1 rule with 3,0 alone: transition_array[3, 0]. Alternatively, if we need to use a 1D array, we can store the rule in the position 3*4 + 0*1 = 12. Although the same scheme is possible for the hash table implementation, I would advise you to use the full indexing scheme instead, since it will not waste more memory if you do, and it is somewhat easier to understand if you use full indices.</p>
<p>Some rules do not need the detailed tables above. For instance, in a system of only two states, where transitions depend on the count of the states of the neighbourhood, we can use a simple array, indexed by one of the states’ counts. Many other schemes are possible: in general, aim for quick lookups and easy specification.</p>
<h3>Edges</h3>
<p>The edges of your simulation might present some problems: edges often serve as unwanted sources, sinks or stabilisers.</p>
<p>A <strong>source</strong> is the origin of outward growth (states change progressively to a specific state in an outward direction).</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>A <strong>sink</strong> is the exact opposite:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>Sources and sinks are emergent properties of the CA system, and are not physical attributes of the cells.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot186" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1861.png" alt="screenshot186" width="144" height="108" align="left" /> A <strong>stabiliser</strong> is a section that keeps neighbouring states fixed. For example, in the fire simulation (described below), there is an unnatural wall of fire around the edges at the end of the simulation.</p>
<p>There are several ways you can handle edges:</p>
<p><strong>Ignore them.</strong> When the edge anomalies are acceptable, it is best not to complicate the model. This is only possible if the rules are specified in a way that does not require state counts to sum to the size of the neighbourhood. For example, if there is a rule “if num_states_fire &gt; 1, then …”.</p>
<p><strong>Wrap around.</strong> This solution is very elegant, easy to implement, and its effects are easy to understand. However, it is usually easy to see that the world has been wrapped in this way, and hence it is not always a visually a satisfactory solution. It is possible, however, to simulate a grid bigger than displayed area (say about double). This will hide the fact that it is wrapped, but still give you the benefits of having a world without any discontinuities.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="wrapped" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/wrapped.png" alt="wrapped" width="88" height="88" align="left" /> In the CA system shown left, we want to calculate the next state of the grey cell. Two neighbours fall outside the edges. If we wrap around, we use the four red squares as shown.</p>
<p><strong>Reflection.</strong> Use a neighbouring state to perform calculations.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="reflect" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/reflect.png" alt="reflect" width="88" height="88" align="left" /> The CA system shown left is the same situation as above. If we use neighbouring states for the cells beyond the edges, we use the state of the grey cell (twice!), in addition to the two red cells shown.</p>
<p><strong>Fix their states. </strong>The edges can be given special, constant states that make the CA behave as intended. Finding the right state(s) for the edges might be difficult.</p>
<p>An implementation trick that applies to the last three edge-handling techniques is to include a border in your simulation. For the Von Neumann and Moore neighbourhoods, this border is only one cell thick.</p>
<p>This border is used for updates like all other cells, but is itself updated differently. The update rules for wrapping and reflection will simply copy states from the right places; the border for fixed states will never be updated.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="edges_implementation" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edges-implementation.png" alt="edges_implementation" width="123" height="123" align="left" /> In the figure, hatched cells are updated according to the special rules of the edge-handling scheme – in this case, wrapping is used, so they are simply copied from the appropriate cells. All other cells are updated normally. Note that here we do not need special logic for updating the grey cell.</p>
<h2>A Few Examples</h2>
<p>(Also see the downloads at the bottom of the post).</p>
<h3>Heat</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot210" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot210.png" alt="screenshot210" width="144" height="108" align="left" /> Here, continuous states (floats between 0 and 1) are used. Every cell is updated to a weighted average of its Moore neighbourhood cells: corners have a smaller weight than other cells. For this simulation, heat sinks and sources have been added: they keep the cell’s temperature at 0 and 1 respectively.</p>
<h3>City Roads</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="roads" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/roads.png" alt="roads" width="144" height="108" align="left" /> This simulation use separate neighbourhoods for creating and destroying a road. The creation neighbourhood is an extended Von Neumann neighbourhood; the destruction neighbourhood is a Moor neighbourhood. Creation and destruction is according to probabilities based on the count of neighbouring roads.</p>
<h3>Influence</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="anger" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/anger.png" alt="anger" width="288" height="216" align="left" /></p>
<p>This simulation models human emotion as influenced by others. A character has an internal state, and an externally visible state. Characters can only observer the external state of their neighbours. The internal state is then a modified: a character surrounded by angry people will itself become angry, and so on. The external state is probabilistically determined by the internal state.</p>
<h3>Disease Spread</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="epeidemic" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/epeidemic.png" alt="epeidemic" width="288" height="216" align="left" /> For our game <a href="http://www.luma.co.za/labs/2007/10/15/epidemic/">Epidemic</a>, <a href="http://blog.cunnington.co.za/">Chris</a> and I used a simple diffusion model. We used a floating-point number for the state, and represented the number of infected people in a cell. We used different colours for different ratios to visualise infection. At each time step, a cell would become infected by an amount proportional to that of the neighbourhood, with some random scaling.</p>
<h2>Visualising States</h2>
<h3>Versions of tiles</h3>
<p>A very effective way of making CA simulations more impressive is to have more than one tile for each state, and display them randomly. This is especially helpful for hiding regularity in off-line simulations. Tile sets with different versions for corners, edges, and central regions can drastically improve the look of the game, although it complicates choosing the correct tile version. In addition, it means you need tiles for various combinations of states. Assuming we can rotate and reflect tiles, in the fire example with three states, we need the following tiles:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="250" valign="top">3 centre tiles</td>
<td width="59" valign="top"><img style="display: inline" title="centre" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/centre1.png" alt="centre" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 straight-edge tiles</td>
<td width="59" valign="top"><img style="display: inline" title="edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edge1.png" alt="edge" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 diagonal line tiles</td>
<td width="59" valign="top"><img style="display: inline" title="diagonal" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/diagonal1.png" alt="diagonal" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 cross tiles</td>
<td width="59" valign="top"><img style="display: inline" title="cross" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/cross1.png" alt="cross" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">6 corner tiles</td>
<td width="59" valign="top"><img style="display: inline" title="corner" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/corner1.png" alt="corner" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 half-straight tiles</td>
<td width="59" valign="top"><img style="display: inline" title="half_edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/half-edge1.png" alt="half_edge" width="49" height="49" /></td>
</tr>
</tbody>
</table>
<p>This is 21 tiles for only three states. It is advisable to automate tile creation.</p>
<h3>Tile <a name="_Toc226913823"></a></h3>
<p>States can be animated. Instead of displaying a single tile, display an animation sequence. You will need to think about how to start and stop these animations so that they are seamless. For instance, you can make all animation sequences the same length, and only update states between animation sequences.</p>
<p>You can also increase the seamlessness of the simulation by animating transitions between states. This can be as easy as blending between two tiles over a period of time (assuming that updates are made far enough apart).</p>
<h3>No Tiles</h3>
<p>Instead of using tiles to represent a state of a cell, you can put objects in a cell. For instance, in a plant growth simulation, you can put a number of trees in the cell depending on the state. The advantages of this are:</p>
<ul>
<li>You do not have to create dozens of tiles for variety.</li>
<li>The player can interact with the objects. For instance, the plant placement of trees can hinder a player’s movement.</li>
</ul>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="detail" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/detail1.png" alt="detail" width="140" height="108" align="left" /> This shows a simple forest simulation. Trees grow and die depending on the surrounding trees. This system uses a grid, but not tiles: trees can grow in random positions in tiles. For this simulation, three random coordinates have been chosen for each cell at the beginning of the simulation. Depending on the states, one, two, or three trees will be drawn at these points. Choosing a fixed set of points makes it easier to draw trees at the same coordinates every tick. A somewhat more complicated simulation can choose new points whenever a new tree comes into being.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot191" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1911.png" alt="screenshot191" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot193" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1931.png" alt="screenshot193" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot196" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1961.png" alt="screenshot196" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<h2>CA Enhancements</h2>
<p>The images below show three frames from a simple fire simulation.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot181" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1811.png" alt="screenshot181" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot182" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1821.png" alt="screenshot182" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot183" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1831.png" alt="screenshot183" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>The green is grass (Dry Bush), the orange is fire (Burning Bush) and the brown is burnt grass (Charcoal).</p>
<p>As you can see, the simulation captures some features of a fire:</p>
<ul>
<li>fire grows outward,</li>
<li>grass only burns once,</li>
<li>grass needs fire to catch fire (there is no spontaneous combustion).</li>
</ul>
<p>Even so, the symmetry and regularity makes this fire very unconvincing. Below we look at some ideas to enhance a simple CA simulation.</p>
<h3>Probabilistic State Transitions</h3>
<p>Instead changing to some specific state based on the surrounding states, you can change to any state with some probability. These probabilities depend on the surrounding states, and can possibly be zero.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot167" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1671.png" alt="screenshot167" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot168" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1681.png" alt="screenshot168" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1692.png" alt="screenshot169" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1702.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1712.png" alt="screenshot171" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot172" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1721.png" alt="screenshot172" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot173" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1731.png" alt="screenshot173" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot174" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1741.png" alt="screenshot174" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot175" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1751.png" alt="screenshot175" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Adding probability to the mix can have several advantages:</p>
<p><strong>It introduces variability in patterns.</strong> This means a specific (perhaps the start-up pattern) will not always produce the same results.</p>
<p><strong>It can enhance the organic look of the system.</strong> Cross and squares patterns are common in deterministic CA systems. For many purposes, this is unsatisfactory (have you ever seen a fire spreading as a growing square?) Adding probabilistic state changes will make the patterns more organic and varied.</p>
<p><strong>It can make discreet behaviour more continuous.</strong> For example, two common &#8220;problems&#8221; with CA systems are exponential growth (where all cells go to a certain state outwards very quickly), or sudden death (where all cells go to a certain state very quickly inwards). The problem is often that a single change in the update rules results in a exponential growth system to become a sudden death system, with seemingly no way to get a &#8220;sweet spot&#8221;. If states can only change with a certain probability, tweaking the probabilities allows you to get intermediate patterns (stable growth, equilibrium, or stable death).</p>
<p><strong>It allows you to control the speed of the simulation.</strong> It is especially helpful to slow down a simulation without making it more granular (in the time dimension). It is useful to multiply all your probabilities with a global parameter that you can tweak to control the speed.</p>
<p>Note that in the example above, certain cells did not burn at all – per chance, they did not caught fire when their neighbours were burning. Timers (see below) can reduce or eliminate this effect.</p>
<p>Adding randomness can increase the emergence, and hence also unwanted emergence, so care must be taken that the simulation is always valid.</p>
<h3>Tile Interpolation</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1693.png" alt="screenshot169" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1703.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1713.png" alt="screenshot171" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Normally, you want your simulation to be as simple as possible. However, when such simple simulations are displayed (visualised), the results can be unsatisfactory. One way to get better visual quality is to use tile (cell) interpolation to make the simulation seem more complicated than it really is. When combined with a bit of randomisation, the effects can be very convincing.</p>
<p>The basic idea is to simulate only every nth cell with the CA approach. Other cells are interpolated. The number of interpolated cells can be adjusted, depending on the detail level required (balanced with the combinatorial number of tiles required!)</p>
<p>In the fire simulation, using only three states makes the simulation seem very primitive. Suppose that we simulate only every second row, and in these, only every second column, and fill the remaining cells depending on their neighbours. We have to create a function that will return a tile for each combination of surrounding tiles:</p>
<p>get_center_tile(north, east, south, west)</p>
<p>Interpolation rules are similar to update rules of the simulation, and hence can easily be as complicated. If this is the case, you would do better to implement more states and not do any interpolation. Interpolation should only be used if it significantly reduces the implementation complexity.</p>
<h3>Timers</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody></tbody>
</table>
</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot177" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1771.png" alt="screenshot177" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot178" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1781.png" alt="screenshot178" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot179" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1791.png" alt="screenshot179" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Some interesting effects can be obtained if each cell has a timer, that is, each cell only updates once the timer expires. Some rule determines when the timer is reset. For instance, the timer can be set:</p>
<ul>
<li>randomly,</li>
<li>as a function of the state,</li>
<li>as a function of the surrounding cells,</li>
<li>as a function of another property of the tile (*1),</li>
<li>as a function of some external process (*2).</li>
</ul>
<p>(*1) For instance, if each cell has an associated &#8220;burning capacity&#8221; parameter, (simulating material types), a fire state timer can be set in proportion to this parameter.</p>
<p>(*2) For example, we can set timers according to a wind factor.</p>
<p>Timers can have the following effects:</p>
<ul>
<li>add some randomness to a simulation,</li>
<li>slow the simulation down,</li>
<li>smear the simulation (for example, in the fire simulation, the burning border is much thicker, and no cells are skipped).</li>
</ul>
<p>Although you can often implement your grid cells as classes (or structs, or whatever aggregating construct your language provides) with states and timers embedded, it is simpler (on more efficient) to have separate integer grids – one for states and one for timers.</p>
<p>Note that if timers do not have the same expiration time, you the CA system is asynchronous and the behaviour can differ dramatically from a synchronous CA system. Thus, you should include timers early in the development process, so that their effect does not force you to re-tweak all the parameters.</p>
<h2><a name="_Toc226913828"></a></h2>
<p>If your world is big, you cannot run the CA for the whole world at every time step – it will kill performance. Below are some ideas for improving performance.</p>
<h3><a name="_Toc226913829"></a></h3>
<p>Instead of simulating the entire world, you can only simulate the part that is relevant to the game, usually the visible region of the game. A simple technique is to use a wrapped grid, similar to the grids used for the visual port in scrollable 2D games. This grid can be slightly larger than the visible grid, so that it allows cells to update naturally for a few iterations before they become visible, and so increase the illusion of a persistent world.</p>
<p>To hide that fact that you are only simulating a very small piece of the world, you must update “new” cells appropriately. There are several options:</p>
<p><strong>Update cells to a natural starting state.</strong> In many cases, this solution is adequate, especially if you simulate a slightly larger grid than is visible.</p>
<p><strong>Copy states from the existing simulation.</strong> Here you can copy neighbouring cells, or randomly from a nearby region. Copying from nearby cells promotes spatial coherence.</p>
<p><strong>Initialise states statistically.</strong> Based on a neighbourhood of cells, each cell is initialised probabilistically. For example, each cell can be initialised randomly to one of three neighbouring cell’s states.</p>
<p><strong>Use hierarchical modelling.</strong> Use another CA system that represents the entire world in very low detail, and use this to initialise the cells of the high detail version. Note that both the states and the update rules will differ for the high and low detail simulations. Use probabilities to prevent homogeneous systems. You can even use several levels of detail, and incorporate them as needed. Beware the extra implementation complexity, though!</p>
<p>This technique does not work when the world is should be changed permanently.</p>
<h3><a name="_Toc226913830"></a></h3>
<p>Instead of only simulating a part of the world, you can only update a part of the world. This requires enough memory for the whole world, but only processing power for the cells you wish to update. This method has the advantage of real persistence, thus permanent changes can be reliably simulated. Which cells you update will determine how your simulation will play out:</p>
<ul>
<li>Update all visible cells (or a slightly larger region). This is the most natural update scheme, and its effects are similar to partial simulation described above.</li>
<li>Divide the world into discontiguous regions, and update a different region each time step. For example, divide the world into two sets: one contains every other cell, the other the rest, and update these two sets alternately. To save a significant amount of processing, you need many sets. To hide patterns in the updates that might break the illusion of a continuous world, the sets should be irregular. This method has the advantage that real things happen off screen. On the down side, it slows down the simulation significantly.</li>
<li>Combine the two methods above.</li>
</ul>
<p>Partial updating, like the inclusion of timers, lead to an asynchronous system, and hence the behaviour might be very different from that of a fully updated system.</p>
<h3><a name="_Toc226913831"></a></h3>
<p>In certain cases, simulations can be baked offline and be used in games. This means you perform the simulation before the time, and record each frame. The game then reads these frames, and plays them back.</p>
<p>Various schemes are possible to get more with less. For instance, you can also interpolate the simulation in time. With some thought, you can simulate events in a way that they can be looped, stacked together, and started and stopped unobtrusively. This means you can blend them with the interaction in a way that will not make it obvious that the simulation has been performed off-line.</p>
<h3>Unwanted Emergence</h3>
<p>Not all emergence is good, and you might find it hard to prevent certain behaviours. If the unwanted behaviour is only visual, and it occurs only rarely, it might be acceptable. However, if behaviour impacts play negatively, it must be prevented.</p>
<p>As with all tweaking, you should not spend too much time fumbling around. To proceed more &#8220;scientifically&#8221;, ask yourself the following questions:</p>
<ul>
<li>Is there a way to detect (measure objectively) the unwanted behaviour?</li>
<li>Instead of tweaking your CA, can you detect-and-recover system be used?</li>
<li>Is the behaviour continuous? In other words, is there a degree of badness, or is it either good or bad?</li>
<li>If it is continuous, is it feasible to kick in a preventative system? (When the badness goes above a threshold, updates are processed differently).</li>
<li>Is it feasible to find a set of parameters through an optimisation algorithm (for instance, genetic programming)? It might even be possible to search exhaustively for a solution.</li>
<li>Is my model too complex? Try to eliminate states and simplify transition rules. You might even consider breaking your simulation into two or more independent CA systems.</li>
<li>If you find yourself struggling to tweak the parameters for too long, you should perhaps look for a better model that is less sensitive to the exact parameters.</li>
</ul>
<h2>Links</h2>
<h3>Online Demo</h3>
<p><a href="http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata">http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata</a> Browswer-based demo with ActionScript source code.</p>
<h3>General</h3>
<p><a href="http://cell-auto.com/">http://cell-auto.com/</a> A nice breakdown of various topics related to Cellular Automata. The article on <a href="http://cell-auto.com/optimisation/">optimisation</a> is especially interesting.</p>
<p><a href="http://www.collidoscope.com/modernca/">http://www.collidoscope.com/modernca/</a> Contains many non-traditional variations of cellular automata.</p>
<p><a href="http://www.fourmilab.ch/cellab/">http://www.fourmilab.ch/cellab/</a> Application for exploring cellular automata.</p>
<h3>Applications and Implementation</h3>
<p><a href="http://realtimecollisiondetection.net/blog/?p=57">http://realtimecollisiondetection.net/blog/?p=57</a> Path finding using cellular automata.</p>
<p><a href="http://www.ibm.com/developerworks/java/library/j-camusic/">http://www.ibm.com/developerworks/java/library/j-camusic/</a> Cellular Automata and music (interesting way of creating procedural music).</p>
<p><a href="http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html">http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html</a> About using lazy, infinite containers for cellular automata.</p>
<p><a href="http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html">http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html</a> Graphics applications for cellular automata – lots of videos!</p>
<h3>Game Design</h3>
<p><a href="http://www.gamestudies.org/0102/pearce/">http://www.gamestudies.org/0102/pearce/</a> An article about game design.</p>
<p><a href="http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf">http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf</a> A thesis that looks at game design from a emergence perspective.</p>
<p><a href="http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01">http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01</a> Will Wright and Brian Eno on generative systems.</p>
<h2>Downloads</h2>
<h3>Game Maker Demos</h3>
<ul>
<li>Requires Game Maker 7.</li>
<li>Contains 9 demos.</li>
</ul>
<p><a href="http://www.code-spot.co.za/downloads/game_maker/ca_demos.zip">ca_demos.zip</a> (135 KB)</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fcode-spot.co.za%2F2009%2F04%2F09%2Fcellular-automata-for-simulation-in-games%2F&amp;linkname=Cellular%20Automata%20for%20Simulation%20in%20Games"><img src="http://code-spot.co.za/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>5 Tips for Prototyping Slow Algorithms</title>
		<link>http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=5-tips-for-prototyping-slow-algorithms</link>
		<comments>http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 07:20:21 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[grids]]></category>
		<category><![CDATA[maintainability]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[prototyping]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[slow algorithm]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=216</guid>
		<description><![CDATA[
(Photo by  Darren Hester)
Some algorithms take a long time to return their results. Whether it is because the algorithm has to operate on a huge data set, or because it has combinatorial complexity; every time you run it you have to wait minutes or even hours for the thing to finish, making errors very expensive.
This [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/11/2054205239-334a519d0e.jpg" alt="2054205239_334a519d0e" width="500" height="375" /></p>
<p>(Photo by  <a href="http://www.flickr.com/photos/ppdigital/">Darren Hester</a>)</p>
<p>Some algorithms take a long time to return their results. Whether it is because the algorithm has to operate on a huge data set, or because it has combinatorial complexity; every time you run it you have to wait minutes or even hours for the thing to finish, making errors very expensive.</p>
<p>This post gives some advice on how to prototype slow algorithms with as little frustration as possible. We assume that this algorithm is being implemented experimentally – that is, you will tweak it and change it often before it is finished (it is not the kind of algorithm you type in straight from a text book). For example, I used the ideas outlined here while playing with the <a href="http://code-spot.co.za/2008/11/07/a-simple-procedural-texture-algorithm/">texture generating algorithm of the previous post</a>.</p>
<p><span id="more-216"></span></p>
<p>This post is not about optimisation, looking for another algorithm, implementing it in another (faster) language (C++) or writing correctness tests for it. Some of the suggestions go against good programming practices for production code, and you should not use them for that.</p>
<p>The idea behind these suggestions is:</p>
<ul>
<li>to minimise error (that would force a rerun after correcting it);</li>
<li>to minimise duplication of calculation between successive runs; and</li>
<li>to minimise losing a better procedure or parameter set (that would force several reruns in trying to reconstruct it from memory).</li>
</ul>
<p>I will assume that your code is divided in two parts:</p>
<ul>
<li>a function (and its helper functions) that forms the algorithm; and</li>
<li>a test harness.</li>
</ul>
<p>To illustrate the ideas proposed below, we will use the following experimental blur algorithm as an example. I give it here in Python, but the tips are not language specific.</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">def blur(grid, repeat_count, window_radius):
    window_area = (window_radius * 2 + 1)**2
    tmp_grids = [None] * repeat_count</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">    for i in range(repeat_count):
        tmp_grid[i] = Grid2D(grid.dims)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">        for index in grid.index_iter():
            for window_cell in grid.wrapped_square_iter(index, window_radius):
                sum += window_cell
            tmp_grid[i][index] = sum / window_area</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">        grid = tmp_grid[i]</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">        new_grid = Grid2D(grid.dims)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">        for index in new_grid.index_iter():
            new_grid = tmp_grid[floor(random() * repeat_count)]</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">        return new_grid

def demo_blur():
    grid = load_image(‘bar.png’)
    grid = to_grey(grid)
    grid = blur(grid, 20, 5)
    write_image(grid, ‘bar_blur.png’)</pre>
</div>
<h2>1. Implement a quick-run feature</h2>
<p>A quick-run is where all loops and data structure sizes are set to the minimum necessary to make all the code run. This is to prevent large amounts of processing time before hitting a run-time error because of a small mistake near the end of the algorithm. This step is especially helpful if you use a dynamic language, where there is less help from the compiler to check validity of code.</p>
<p>In our example, there are three factors that determine the length of the algorithm:</p>
<ul>
<li>the image size;</li>
<li>the repeat count; and</li>
<li>the window radius.</li>
</ul>
<p>We can implement a quick-run feature by changing our harness as follows:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">quick_run = True

if quick_run:
    test_base_name = '8x8'
    test_image = test_base_name +'.png' #This is an 8 x 8 image.
    repeat_count = 2
    window_radius = 1
else:
    test_base_name = 'bar'
    test_image = test_base_name +'.png'
    repeat_count = 20
    window_radius = 5

def demo_blur():
    grid = load_image(test_image)
    grid = to_grey(grid)
    grid = blur(grid, repeat_count, window_radius)
    write_image(grid, ‘blur.png’)</pre>
</div>
<p>Every time we make a change, we first run the program with quick_run set to True just to make sure we have not introduced any errors in the code. If you use a language that supports #define macros (C and C++) or some similar functionality, this can be implemented much more seamlessly.</p>
<p>Be careful for degenerate cases that skip loops – make sure all loops run at least once.</p>
<h2>2. Consider using disk-caching for intermediate results</h2>
<p>If it is faster to load a data structure from disk than to recreate it, you might gain a considerable saving in time by saving it to disk the first time it is created, and loading it thereafter.</p>
<p>In our example, we can store the temporary grids cache the temporary grids on disk by changing the function, allowing us to tweak part of the algorithm following the comment more effectively:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">def blur_once(grid, window_radius, step):
    fname = test_image_base + '_blur_once_' + str(window_radius) + '_' + str(step)
    f = file(fname)

    if f.exists():
        return load_image(f)
    else:
        tmp_grid = Grid2D(grid.dims)
    for index in grid.index_iter():
            for window_cell in grid.wrapped_square_iter(index, window_radius):
                sum += window_cell
            tmp_grid = sum / window_area
        save_image(tmp_grid, fname)
    return tmp_grid

def blur(grid, repeat_count, window_radius):
    window_area = (window_radius * 2 + 1)**2
    tmp_grids = [None] * repeat_count

    for i in range(repeat_count):
        tmp_grid[i] = blur_once(grid, window_radius, i)
        grid = tmp_grid[i]

    ### Part that can be tweaked follows ###
    new_grid = Grid2D(grid.dims)

    for index in new_grid.index_iter():
        new_grid = tmp_grid[floor(random() * repeat_count)]

    return new_grid</pre>
</div>
<h3>Guidelines</h3>
<p>When caching is used carefully, it can save time. But it can also waste a lot of time.</p>
<ul>
<li>Use it if you use one test case often. In our example, we would not gain much if we tested with a different image every time. But if we used one or perhaps a few images, you can reap the benefits.</li>
<li>When tweaking different parts of the algorithm, caching might become a hindrance. Never cache results that depend on your current tweaking. Not only will the extra disk saves slow things down, but you might be confusing old results from the cache instead of the results you actually need.</li>
<li>Make sure that the filename is unique for the function and all the input parameters. You might use results from the cache for the incorrect inputs without realizing it, leading to very frustrating debugging. This works hand-in-hand with tip 4.</li>
<li>Remember to stabilise randomness; that is, seed the randomiser at appropriate spots. (It is, of course, something you should generally do for debugging and unit tests / regression tests).</li>
<li>For a little extra work, you can avoid bugs due to a non up-to-date cache, at least in some cases. Perform the algorithm on a subset or sample of the data, and compare this with the cache. Signalling inconsistencies can help flush out bugs. You can even modify the caching to update automatically when such an inconsistency appears – but you should still always signal cache misses, so that you can immediately see when your cache is failing, perhaps because of a bug or unstable randomisation.</li>
<li>Make your cache easy to clear (define a simple function for this).</li>
<li>Make it easy to disable caching for a run.</li>
<li>If you use an interpreted language, you can often use a “soft-cache” instead. This just means that you store intermediate results in variables, and only recalculate them when necessary. This can be a powerful method, but in my experience it requires a lot of mental maintenance, and is therefore error-prone. Because we are dealing with slow algorithms, a crash during an interactive session might be disastrous.</li>
</ul>
<h2>3. Use “yield” to return intermediate results for easy inspection&#8230;</h2>
<p>&#8230;if your programming language allows this (C#, Ruby, Python). When prototyping an algorithm, it is often helpful to inspect (or analyse) intermediate results. Doing this can clutter up the code, especially since you want to put it in and take it out as the need arises.</p>
<p>Here is how we can modify our code:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">RESULT = 0
BLUR_ONCE = 1

def blur(grid, repeat_count, window_radius):
    window_area = (window_radius * 2 + 1)**2
        tmp_grids = [None] * repeat_count

    for i in range(repeat_count):
        tmp_grid[i] = blur_once(grid, window_radius, i)
        yield tmp_grid[i], BLUR_ONCE, i

        grid = tmp_grid[i]
    new_grid = Grid2D(grid.dims)

    for index in new_grid.index_iter():
        new_grid = tmp_grid[floor(random() * repeat_count)]

    yield new_grid, RESULT, 0

def demo_blur():
    grid = load_image(test_image)
    grid = to_grey(grid)

for result, result_id, step in blur(grid, repeat_count, window_radius)
    if result_id == BLUR_ONCE:
        if step % 2 == 0:
            write_image(res, ‘blur_once_’ + test_base_name + ‘_’ + str(step) + ‘.png’)
        elif RESULT_ID == RESULT:
            write_image(result, ‘blur.png’)</pre>
</div>
<p>Note that you can change what you want to inspect in one place. This is even more useful in complicated or deeply nested algorithms. Using an extravagant language feature such as yield also makes it easier to port the code to the production version – it is easier to spot and remove.</p>
<p>If your language does not support yielding, you can implement a inspect function and still have s astructure very similar to the above:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">RESULT = 0
BLUR_ONCE = 1

def blur(grid, repeat_count, window_radius):
    window_area = (window_radius * 2 + 1)**2
    tmp_grids = [None] * repeat_count

    for i in range(repeat_count):
        tmp_grid[i] = blur_once(grid, window_radius, i)
        inspect(tmp_grid[i], BLUR_ONCE, i)
        grid = tmp_grid[i]

    new_grid = Grid2D(grid.dims)

    for index in new_grid.index_iter():
        new_grid = tmp_grid[floor(random() * repeat_count)]

    inspect(new_grid, RESULT, 0)

    return grid

def inspect(result, result_id, step):
    if result_id == BLUR_ONCE:
        if step % 2 == 0:
            write_image(res, ‘blur_once_’ + test_base_name + ‘_’ + str(step) + ‘.png’)
    elif RESULT_ID == RESULT:
        write_image(result, ‘blur.png’)

def demo_blur():
    grid = load_image(test_image)
    grid = to_grey(grid)

    #The result is inspected in the inspect function; here we can ignore it.
    #We still put it in a variable to remind us that the function returns a result.

    ignore_result = blur(grid, repeat_count, window_radius)</pre>
</div>
<p>Do not split the function (using polymorphism or overloading to prevent the if-elif logic). The point is that we want a single place where we can choose whether to output the result to disk or not.</p>
<h2>4. When tweaking functions, make copies rather than tweaking in-place</h2>
<p>Do this even for relatively small changes. Number functions, and associate saved results with the version of that function. One of the most frustrating things is when a change has unwanted effects, and you can’t undo it (and can’t remember how it was when working). Just as frustrating is when you have several results, and do not know which result belongs with which version of the algorithm. Being careful in this regard will prevent long searches for the right settings. It will also make caching (Tip 2) safer.</p>
<p>Under normal coding circumstances, you would refractor these versions to save code and promote maintainability. For prototyping code, I would not suggest this – just copy and paste the function, change the version number, and make the necessary changes in place. Refactoring introduces more room for error – enough to invalidate this tip. Of course, in situations where you want to check out different combinations of algorithms, you might need to refactor after all. As always, do not refactor without the protection of unit tests.</p>
<p>The above applies especially when changing library code – rather make a copy of the library code outside the library (perhaps only a single function or class), make the change there, and use the copy. This allows you to be quick and dirty; you can always refactor the change back in if the change is also useful in other application.</p>
<p>And if you think this approach will lead to a refactoring nightmare later on, you are right. But later on is the right time to deal with it – now you are designing an algorithm, and you need all your brain power. The point of this is to not mess up any existing (tested and working) code.</p>
<h2>5. Implement an early-warning system</h2>
<p>Even when you do not always know exactly what the state of a data structure <em>should</em> be, you often know what it should not be (for instance, empty). One mistake I make often is to process the wrong variable, for instance:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">grid = do_something(grid)
new_grid = so_something_else(new_grid) #Should really work on grid</pre>
</div>
<p>To help eliminate this problem, I implement a few very quick tests to flag suspicious conditions. What tests you implement depends on your application; here are a few generic ones:</p>
<ul>
<li>Test for emptiness</li>
<li>Test for uniformity (for example, to detect all-black images)</li>
<li>Test for no-change after processing</li>
<li>Test for excessive deviations after processing</li>
</ul>
<h3>Guidelines</h3>
<ul>
<li>Use these tests in assert statements if your language supports them.</li>
<li>When working with large data structures (such as images), it is important not to test the entire structure, but rather just a sample. Your tests should not take any time to run at all! For images, even a sample of 10 pixels can be enough in many situations.</li>
<li>If you take a random sample, it is a good idea to use a separate randomiser for these tests. This way seeding the randomiser elsewhere (to stabilise for caching, for example) won’t affect the test samples negatively – it is better to test with different sample sets each time.</li>
<li>Do not strive for mathematical correctness and completeness (unless this is easy to achieve) – rather use simple rules that will flag extreme deviations. For example, a blur should not significantly change the average brightness of a sample on an image. Although bounds for his can be calculated exactly, broader bounds (that are easy to estimate) will already flag many mistakes in the code.</li>
<li>Avoid complicated test code; in particular, avoid complicated sampling. Again, we are not striving for the mathematical best sampling method – that is for the production version.</li>
<li>Test your tests aggressively! There is nothing like a faulty test to waste time.</li>
<li>Do not halt the algorithm on a failed test where only a sample is used – output the suspect data structure to disk and inspect it first to make sure it is not a false alarm. If it is a false alarm, the algorithm is not stopped needlessly, and you do not have to put in (unnecessary) code to check what is going on. Remember to increase the sample size of the sample algorithm before the next run.</li>
<li>It is good to start with very crude tests, and refine them as you get closer to the final version of the prototype. Obviously, tests for the production implementation should be as exact as possible.</li>
</ul>
<h2>Other methods</h2>
<p>What protection devices do you use for prototyping slow algorithms? Let me know in the comments!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fcode-spot.co.za%2F2008%2F11%2F11%2F5-tips-for-prototyping-slow-algorithms%2F&amp;linkname=5%20Tips%20for%20Prototyping%20Slow%20Algorithms"><img src="http://code-spot.co.za/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Force Field Editor v1.0</title>
		<link>http://code-spot.co.za/2008/10/29/force-field-editor-v10/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=force-field-editor-v10</link>
		<comments>http://code-spot.co.za/2008/10/29/force-field-editor-v10/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 15:46:01 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[force field]]></category>
		<category><![CDATA[quadtree]]></category>
		<category><![CDATA[vector field]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=161</guid>
		<description><![CDATA[
Vector fields are used in certain AI and simulation techniques. The tool below allows you to paint a vector field. These files can be saved in XML format, that can easily be loaded into another application.

There are five brushes:

The Set Direction brush keeps the size of the underlying vector the same, but changes the size [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/pull.png" alt="pull" width="500" height="357" /></p>
<p>Vector fields are used in certain AI and simulation techniques. The tool below allows you to paint a vector field. These files can be saved in XML format, that can easily be loaded into another application.</p>
<p><span id="more-161"></span></p>
<p>There are five brushes:</p>
<ul>
<li>The Set Direction brush keeps the size of the underlying vector the same, but changes the size to a constant value.</li>
<li>The Set Size brush keeps the size of the underlying vector the same, but changes the direction to a constant angle.</li>
<li>The Attract brush draws all the vectors closer to the mouse cursor.</li>
<li>The Repel brush pushes all vectors away from the mouse cursor.</li>
<li>The Comb brush moves vectors in the same direction as the mouse.</li>
</ul>
<p>The XML file arranges the field into a quadtree. The quadtree compression can be viewed from the program.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="250" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/normal.png" alt="normal" width="240" height="240" /></td>
<td width="250" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/compressed.png" alt="compressed" width="240" height="240" /></td>
</tr>
</tbody>
</table>
<p>To change the brush size, use the &#8216;[' and ']&#8216; keys.</p>
<p>To change the brush options, use the &#8216;-&#8217; or &#8216;=&#8217; keys.</p>
<p>This is the first version of this program, so there are many missing features. For example, the size of the field can not be changed yet. If you find it useful, let me know in the comments!</p>
<h2>Download</h2>
<h3>Windows Executable</h3>
<p><a href="http://www.code-spot.co.za/downloads/tools/force_field_editor_v1_0.exe">force_field_editor_v1_0.exe 3.3 MB</a></p>
<p>Requires <a href="http://java.com/en/download/manual.jsp">Java Runtime Environment</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fcode-spot.co.za%2F2008%2F10%2F29%2Fforce-field-editor-v10%2F&amp;linkname=Force%20Field%20Editor%20v1.0"><img src="http://code-spot.co.za/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/10/29/force-field-editor-v10/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generating Random Numbers with Arbitrary Distributions</title>
		<link>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=generating-random-numbers-with-arbitrary-distributions</link>
		<comments>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 18:16:59 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[distribution function]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random number generation]]></category>
		<category><![CDATA[response curve]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[Special Numbers Library]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=123</guid>
		<description><![CDATA[
For many applications, detailed statistical models are overkill. Instead, we can get away with a rough description of the distribution &#8211; not in mathematical formula form, but just as a graph with a few sample points.
For example, when trying to model the traffic around a school, you might know that the graph looks something like [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img zemanta-action-click">
<p class="zemanta-img-attribution">For many applications, detailed statistical models are overkill. Instead, we can get away with a rough description of the distribution &#8211; not in mathematical formula form, but just as a graph with a few sample points.</p>
<p class="zemanta-img-attribution">For example, when trying to model the traffic around a school, you might know that the graph looks something like this:</p>
<p class="zemanta-img-attribution"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/school.png" alt="school" width="481" height="289" /></p>
<p class="zemanta-img-attribution">The input is the number of minutes before the first bell rings, and the output the number of children dropped off at that time. You know that most kids are brought before the bell rings, and that the closer to the bell, the more kids are being brought every minute. Only a few kids are late.</p>
<p class="zemanta-img-attribution">This tutorial describes how to generate random numbers that can generate a distribution described by an arbitrary (piece-wise linear) curve, as the one above.</p>
<p class="zemanta-img-attribution"><span id="more-123"></span></p>
<h2>Implementation</h2>
</div>
<h3>1. Calculate an accumulative probability</h3>
<p>The first step is to run an accumulative sum of our original sample points. The following code snippet shows how it can be done in C++; the array &#8220;samples&#8221; contains the original samples.</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 1; i &lt; n; i++)
{
    samples[i] += samples[i - 1];
}</pre>
</div>
<p>   The snippet above does the calculations in-place, but it is not necessary, as is shown in the snippet below:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">newSamples[0] = samples[0];

<span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 1; i &lt; n; i++)
{
    newSamples[i] = samples[i] + newSamples[i - 1];
}</pre>
</div>
<p>   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/accumulative.png" alt="accumulative" width="481" height="289" /> The graph above shows the accumulative probability density.</p>
<h3>2. Calculate inverse sample points</h3>
<p>This step is easy &#8211; we simply swap the input and output samples. It is not necessary to do this explicitly, just swap them in the argument list of the function call in the next step.  <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/inverse.png" alt="inverse" width="481" height="289" /></p>
<h3>3. Interpolate between samples</h3>
<p>I use a special data structure that makes it very easy to compute the interpolations from discreet sample points: the response curve. There are two varieties. The ordinary response curve, with uniformly spaced samples, and the xy-response curve, where samples can be arbitrarily spaced.  <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/u-response.png" alt="u-response" width="481" height="289" /> <strong>Ordinary Response Curve.</strong> <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/xy-response.png" alt="xy-response" width="481" height="289" /> <strong>XY-Response Curve.</strong> The implementation is very simple, so I won&#8217;t describe it here. A C++ implementation is available in the <a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a>; a Python implementation is available with the example below. Here I simply explain the usage as it relates to this tutorial.  We proceed as follows:</p>
<ul>
<li>First, we construct an xy-response curve from our samples of the inverse accumulative probability.</li>
<li>Then we sample this curve at regular intervals, and load it into a ordinary response curve (we do this, simply because the ordinary response curve is much faster than the xy-version).</li>
</ul>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #008000">//...</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">int</span> oldSampleCount = 7;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">int</span> newSampleCount = 20;

<span style="color: #0000ff">float</span> inputMin = 0.0f;
<span style="color: #0000ff">float</span> inputMax = 3.2f;

<span style="color: #008000">//note: input and output is swopped arround, because we want the inverse!</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">XYResponseCurve&lt;<span style="color: #0000ff">float</span>, oldSampleCount&gt; xyCurve(outputSamples, inputSamples);</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 0; i &lt; newSampleCount; i++)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">{</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">    input = ((float) i / (newSampleCount - 1)) * (inputMax - inputMin) + inputMin;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">    uniformOutput[i] = xyCurve(input);</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">}</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">ResponseCurve&lt;<span style="color: #0000ff">float</span>, newSampleCount&gt; curve(inputMin, inputMax, uniformOutput);</pre>
</div>
<p>   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/uniform.png" alt="uniform" width="481" height="289" /></p>
<h3>4. Map uniform random numbers to the input range of the IAPDF, and calculate the output</h3>
<p>Now that we have the response curve, we can map uniform random numbers to the appropriate input range. For the example above, we need to map to the range [0, 3.2]. The snippet below shows how to generate random numbers with the distribution shown above:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #008000">//...create the curve c</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> input = random(); <span style="color: #008000; ">//Uniformly distributed function between 0 and 1.</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> scaledInput = r * (inputMax - inputMin) + inputMin;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> output = curve(scaledInput);</pre>
</div>
<p>   The graph below shows how 10 000 random numbers are distributed. It follows the original graph closely; the discrepancy at -10 is caused by the way samples are counted (all samples between -10 (inclusive) and 0 (exclusive) are counted and plotted at -10.   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/result.png" alt="result" width="481" height="289" /></p>
<h2>Tips and Pitfalls to Avoid</h2>
<ol>
<li>Generate sequences for all intermediary steps.</li>
<li>Use Excel, Calc, or some other spread sheet program to debug these sequences visually when things go wrong.</li>
<li>It is very easy to get confused with input, and output, especially after the swap. Watch out for this!</li>
<li>It is easy to get confused with the number of samples for the various sequences.</li>
<li>If you implement your own Response Curve data structure, unit tests will save you huge amounts of time.</li>
<li>Always make sure that you sample enough points, especially if your original distribution graph has rapid changes in it.</li>
<li>Always confirm that your random output follows the distribution you wanted.</li>
<li>It might be faster to use this method even when mathematical formulas are available.</li>
</ol>
<h2>Downloads</h2>
<h3>Example C++ Source Code</h3>
<p><a href="http://code-spot.co.za/downloads/cpp_examples/arbitrary_distribution.cpp">http://code-spot.co.za/downloads/cpp_examples/arbitrary_distribution.cpp</a> Requires <span style="font-weight: normal;"><a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a></span></p>
<h3>Example Python Source Code</h3>
<p><a href="http://code-spot.co.za/downloads/python_examples/random_distributions.py">http://code-spot.co.za/downloads/python_examples/random_distributions.py</a></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fcode-spot.co.za%2F2008%2F09%2F21%2Fgenerating-random-numbers-with-arbitrary-distributions%2F&amp;linkname=Generating%20Random%20Numbers%20with%20Arbitrary%20Distributions"><img src="http://code-spot.co.za/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>

<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
