<?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>PlanetMarshall &#187; Software</title>
	<atom:link href="http://www.planetmarshall.co.uk/index.php/category/software/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.planetmarshall.co.uk</link>
	<description>Andrew Marshall's blog.</description>
	<lastBuildDate>Mon, 05 Jul 2010 10:21:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Drawing geodesic curves using the Bing maps Silverlight control</title>
		<link>http://www.planetmarshall.co.uk/2010/06/drawing-geodesic-curves-using-the-bing-maps-silverlight-control/</link>
		<comments>http://www.planetmarshall.co.uk/2010/06/drawing-geodesic-curves-using-the-bing-maps-silverlight-control/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 14:52:05 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[bing maps]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=624</guid>
		<description><![CDATA[For an upcoming post I wanted to be able to plot the shortest routes between various positions on the Earth using the Bing Maps Silverlight control. Although since I started working on the problem Bing have provided a similar feature with their Distance Calculator App, the functions are not available for reuse via the public [...]]]></description>
			<content:encoded><![CDATA[<p class="pm_first">For an upcoming post I wanted to be able to plot the shortest routes between various positions on the Earth using the <a title="Bing Maps Silverlight Control" href="http://msdn.microsoft.com/en-us/library/ee681884.aspx" target="_blank">Bing Maps Silverlight control</a>. Although since I started working on the problem Bing have provided a similar feature with their <a title="New Bing Map Apps: Gas Prices, Distance Calculator and Parking Finder" href="http://www.bing.com/community/blogs/maps/archive/2010/05/19/new-bing-map-apps-gas-prices-distance-calculator-and-parking-finder.aspx" target="_blank">Distance Calculator App</a>, the functions are not available for reuse via the public API. Interested developers may just want to skip the maths and just download the code.</p>
<p><a title="Source code in zip file for Silverlight 4.0" href="http://www.planetmarshall.co.uk/code/geodesic.zip">Geodesic source code for Silverlight 4.0</a></p>
<h3>Geodesics</h3>

<a href="http://www.planetmarshall.co.uk/wp-content/gallery/geodesic/geo.png" title="Geodesic showing the shortest distance between Cambridge and New York" class="thickbox" rel="singlepic118" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/118__150x_geo.png" alt="Geodesic " title="Geodesic " />
</a>

<p>The shortest path between two points on an arbitrary surface is called a <a title="Geodesic from MathWorld" href="http://mathworld.wolfram.com/Geodesic.html" target="_blank">Geodesic</a>, and on a sphere, it is a <a title="Great Circle from MathWorld" href="http://mathworld.wolfram.com/GreatCircle.html" target="_blank">Great Circle</a>. Modelling the surface of the earth as a perfect sphere, the shortest distance between any two locations on the surface is then described by a section of a Great Circle, ie an arc that lies on the plane that is described by the vectors between its start and end points and the Earth&#8217;s centre ( see figure 1 ).</p>
<p>With this information, one way ( and the way I have adopted ) to plot such a curve is as follows:</p>
<ol>
<li>Generate the points of the curve in two dimensions using the parametric equation of a circle.</li>
<li>Transform the plane of the 2d curve into 3D space such that it intersects the end points on the sphere, and the sphere&#8217;s centre.</li>
<li>Project the transformed points back into 2D space using the Mercator projection equations.</li>
</ol>
<p><span id="more-624"></span><br />
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996446fe')">&#x25bc;</a> Silverlight Application</div><div id="4c516996446fe" style="display:" class="silverlightControlHost"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="520" height="384"><param name="source" value="http://www.planetmarshall.co.uk/silverlight/Geodesic.xap"/><param name="background" value="#212121" /><!--<param name="minRuntimeVersion" value="2.0.31005.0" />--><param name="enableHtmlAccess" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;"><img src="http://storage.timheuer.com/sl4wp-ph.png" alt="Install Microsoft Silverlight" style="border-style: none; width:520px; height:384px"/></a></object><iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe></div><br /></p>
<h3>A Parametric Representation of a Great Circle</h3>
<p>The <a title="Mercator Projection from MathWorld" href="http://mathworld.wolfram.com/MercatorProjection.html">Mercator projection</a> gives the 2D rectilinear coordinates (x,y) as a function of the latitude and longitude of a point on a sphere.  However, it is easier to draw the point using a typical drawing API, if we have a representation that gives each point of the curve in terms of a single parameter. To derive such a function, we observe that the parametric equation for a circle is given by</p>
<p><center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_dff0240283ce7cf9f64cdadb3800bdeb.png" align="absmiddle" class="tex" alt="\begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} r \cos t \\ r \sin t \end{pmatrix} " /></center></p>
<p>Since a great circle is a rigid transformation of a circle in 3D space, it can also be represented as a function of a single parameter</p>
<p><center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_e36d1dcd973baacdbb738237d538e501.png" align="absmiddle" class="tex" alt="\begin{pmatrix} x \\ y \\ z \end{pmatrix} = \mathbf{R}\cdot\begin{pmatrix} r \cos t \\ r \sin t \end{pmatrix} " /></center></p>
<p>where <img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_e1fd601dbae82a538d518550acb1af19.png" align="absmiddle" class="tex" alt="\mathbf{R}" /> is a 2&#215;3 matrix that transforms the plane circle to a location on a sphere. Using <a title="Spherical Coordinates from MathWorld" href="http://mathworld.wolfram.com/SphericalCoordinates.html">spherical coordinates</a>, the Mercator projection of the curve specified above is then<br />
<center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_6647aae82c601b96bed420e55cc599f2.png" align="absmiddle" class="tex" alt="\mathbf{C}(t) =\begin{pmatrix} \lambda \\ \tanh^{-1} \left(\sin \phi \right)\end{pmatrix} = \begin{pmatrix} \tan^{-1}\left(y/x\right)\\ \tanh^{-1}z \end{pmatrix}" /></center><br />
Where <img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_c6a6eb61fd9c6c913da73b3642ca147d.png" align="absmiddle" class="tex" alt="\lambda" /> and <img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_1ed346930917426bc46d41e22cc525ec.png" align="absmiddle" class="tex" alt="\phi" /> are the longitude and latitude of the point to be projected, respectively. Writing the equation out in full gives,</p>
<p><center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_d08cced312dd3a1446044a0a3c46bd6c.png" align="absmiddle" class="tex" alt="\mathbf{C}(t) =\begin{pmatrix}</p>
<p>\tan^{-1}\left(\frac{R_{2,1}\cos t + R_{2,2}\sin t}{R_{1,1}\cos t + R_{1,2}\sin t}\right)\\<br />
\tanh^{-1}(R_{3,1}\cos t +R_{3,2}\sin t)<br />
\end{pmatrix}<br />
" /></center></p>
<p>Now that we have a suitable parametric equation, we can draw the geodesic with a series of connected line segments by varying the parameter, t.</p>
<blockquote><p>Mathematical note &#8211; the parameterization given by this expression is highly non-uniform, meaning that there are many more points generated in some parts of the curve than in others. The mathematics of generating uniform ( or natural ) parameterizations belongs to the field of differential curve geometry and is beyond the scope of this article ( and my brain ).</p></blockquote>
<h3>Implementation notes</h3>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/geodesic/maps.jpg" title="The upper image shows what happens when aa curve wraps around the map boundary. The lower image shows the effect of splitting the curve at the boundary." class="thickbox" rel="singlepic141" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/141__150x_maps.jpg" alt="Geodesic with Split" title="Geodesic with Split" />
</a>
 Inevitably, the mathematics alone is not sufficient to produce an implementation of a reuseable class for the Bing Silverlight control. There are two main issues to resolve; firstly, it is not immediately obvious how to derive from the provided <a title="Documentation on MapShapeBase from MSDN" href="http://msdn.microsoft.com/en-us/library/microsoft.maps.mapcontrol.core.mapshapebase.aspx" target="_blank"><code>MapShapeBase</code></a> class to create new shape overlays and secondly, how to handle drawing the curves when they &#8216;wrap&#8217; beyond the map&#8217;s viewable area ( this is easier to illustrate than to describe &#8211; see the figure opposite ).</p>
<h4>Inheriting from <code>MapShapeBase</code></h4>
<p>I must confess that I cheated slightly in implementing the <code>MapGeodesicPath</code> class, in that I used <a title="Reflector from Red-Gate. Stop sending them hate mail!" href="http://www.red-gate.com/products/reflector/" target="_blank">Reflector</a> to peer into the implementation of the base class. The existing derivations of this class simply defer to <code>MapShapeBase</code> for most of the work, which they can do since for a <code>MapPolygon</code> and <code>MapPolyline</code> there is a one-to-one relationship between <code>Locations</code>, latitude and longitude points on the map and <code>Points</code>, the actual 2D cartesian coordinates used to draw the shape. For the Geodesic, this is not the case, because we only want to specify the start and ending points of the curve, not every point in between. A solution is to delegate the point generation code to a secondary class, one that can be independently tested.</p>
<h4>Splitting the curves at the map boundary</h4>
<p>When the curves wrap around the map projection, they need to be split at the boundary. This is done by finding the parameter t for the longitude value of the boundary. Where the longitude value is +/- 180, this is straightforward as the equation above reduces to,<br />
<center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_cf469ce48c88ca9ac3edbf1677a182d6.png" align="absmiddle" class="tex" alt="t = -\tan^{-1}\frac{R_{1,2}}{R_{2,2}} " /></center><br />
For other longitude values, we simply offset the longitude values by the required amount, and calculate the value of t for the new matrix.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2010/06/drawing-geodesic-curves-using-the-bing-maps-silverlight-control/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visualizing the Prime Ministerial Debates</title>
		<link>http://www.planetmarshall.co.uk/2010/04/visualizing-the-prime-ministerial-debates/</link>
		<comments>http://www.planetmarshall.co.uk/2010/04/visualizing-the-prime-ministerial-debates/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 08:30:19 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Imaging]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[politics]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=805</guid>
		<description><![CDATA[For the first time, the main Prime Ministerial candidates for the 2010 UK General Elections, will take part in three live debates. Since the BBC have kindly made the full transcripts available, I decided to have a go at analyzing the data and creating a visual representation in the form of word clouds. I am [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/brown_nouns.png" title="Nouns used by Gordon Brown in the first debate" class="thickbox" rel="singlepic131" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/131__140x_brown_nouns.png" alt="Nouns used by Gordon Brown" title="Nouns used by Gordon Brown" />
</a>

<p class="pm_first">For the first time, the main Prime Ministerial candidates for the 2010 UK General Elections, will take part in <a title="Debates page from the BBC" href="http://news.bbc.co.uk/1/hi/uk_politics/election_2010/the_debates/default.stm" target="_blank">three live debates</a>. Since the BBC have kindly made the full transcripts available, I decided to have a go at analyzing the data and creating a <a title="Jump to image gallery" href="#gallery" target="_self">visual representation</a> in the form of word clouds. I am currently working on my own visualization software, but in the meantime these have been done using <a title="Wordle" href="http://www.wordle.net/" target="_blank">Wordle</a>.</p>
<p><span id="more-805"></span></p>
<h3>Preparing the data</h3>

<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/clegg_adj.png" title="Adjectives and Adverbs used by Nick Clegg in the first debate" class="thickbox" rel="singlepic138" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/138__140x_clegg_adj.png" alt="Adjectives and Adverbs used by Nick Clegg" title="Adjectives and Adverbs used by Nick Clegg" />
</a>
The BBC only provides the data in PDF form &#8211; to analyze it we need it in text form. Although this is easily done with Acrobat Reader&#8217;s &#8220;Save as Text&#8221; function, the output it produces is not really suitable for automatic processing, so some work has to be done by hand. This basically involves making sure each speaker&#8217;s comments are headed by their name and some kind of special character to split each record ( here I have used &#8216;@&#8217; ), which took about 15 minutes or so.</p>
<p><a title="First Prime Ministerial debate in raw text form" href="http://bit.ly/9QRrXx" target="_blank">Download </a>the raw text of the first debate.</p>
<p>Having done that, a command line tool such as <a href="http://www.gnu.org/manual/gawk/gawk.html" target="_blank">awk</a> can be used to split the data by speaker. For example, the following command outputs Clegg&#8217;s comments into a separate file:</p>
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c51699656cf9')">&#x25ba;</a>Listing : </div>
<div id="4c51699656cf9">
<pre class="brush: bash; gutter: false;">
awk 'BEGIN {RS=&quot;&quot;; FS=&quot;[@]&quot;} $1==&quot;NC&quot; { print $2 }' debate.txt &gt; clegg.txt
</pre>
</div>
<h3>Parsing the data</h3>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/cameron_verbs.png" title="Verbs used by David Cameron in the first debate" class="thickbox" rel="singlepic137" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/137__140x_cameron_verbs.png" alt="Verbs used by David Cameron" title="Verbs used by David Cameron" />
</a>
<a title="Python homepage" href="http://www.python.org/" target="_blank">Python</a>&#8217;s <a title="The Natural Language Toolkit" href="http://www.nltk.org/" target="_blank">Natural Language Toolkit</a> provides all the functions needed to analyze the text data, such as tokenizing the text by word and even categorizing each word by type, such as proper nouns and prepositions. For example, having extracted Nick Clegg&#8217;s speech as above and read the file as a string using Python, the following commands parse the input for sentences, and then tokenize each word procucing a complete word list.</p>
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c51699657017')">&#x25ba;</a>Listing : </div>
<div id="4c51699657017">
<pre class="brush: python;">
from __future__ import division
import nltk, re, pprint

sentences = nltk.sent_tokenize(text)
tokens=[]
for s = sentences:
 tokens.extend(nltk.word_tokenize(s))
words=[t.lower() for t in tokens]
</pre>
</div>
<p>We can then categorize each word with a <a title="Wikipdeia page on POS tagging" href="http://en.wikipedia.org/wiki/Part-of-speech_tagging">POS tag</a> and extract a list appropriately, for example, using the word tokens above the following extracts all the nouns</p>
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996571d3')">&#x25ba;</a>Listing : </div>
<div id="4c516996571d3">
<pre class="brush: python;">
# this operation takes some time to execute
taggedwords=nltk.pos_tag(words)
nouns=[word for (word,tag) in words if t == 'NN']
</pre>
</div>
<p>Such a list is enough to use with Wordle, however it&#8217;s straightforward to create a word frequency list for use with other software.</p>
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c5169965731a')">&#x25ba;</a>Listing : </div>
<div id="4c5169965731a">
<pre class="brush: python;">
# this operation takes some time to execute
nounfrequencies = nltk.FreqDist(nouns)
</pre>
</div>
<h3>Going further</h3>
<p>Word frequency analyses are fairly straightforward, however NLTK is a powerful library and allows for much more detailed and informative analysis based on grammar and sentence structure. It would be interesting to see the results of a more sophisticated approach.<br />
<a name="gallery"></a></p>
<h3>Gallery of word clouds from the first debate</h3>
<p>
<div class="ngg-galleryoverview" id="ngg-gallery-13">


	
	<!-- Thumbnails -->
		
	<div id="ngg-image-131" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/brown_nouns.png" title="Nouns used by Gordon Brown in the first debate" class="thickbox" rel="set_13" >
				<img title="Nouns used by Gordon Brown" alt="Nouns used by Gordon Brown" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_brown_nouns.png" width="64" height="41" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-132" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/cameron_nouns.png" title="Nouns used by David Cameron in the first debate" class="thickbox" rel="set_13" >
				<img title="Nouns used by David Cameron" alt="Nouns used by David Cameron" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_cameron_nouns.png" width="64" height="41" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-133" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/clegg_nouns.png" title="Nouns used by Nick Clegg in the first debate" class="thickbox" rel="set_13" >
				<img title="Nouns used by Nick Clegg" alt="Nouns used by Nick Clegg" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_clegg_nouns.png" width="64" height="40" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-135" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/brown_verbs.png" title="Verbs used by Gordon Brown in the first debate" class="thickbox" rel="set_13" >
				<img title="Verbs used by Gordon Brown" alt="Verbs used by Gordon Brown" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_brown_verbs.png" width="64" height="41" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-137" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/cameron_verbs.png" title="Verbs used by David Cameron in the first debate" class="thickbox" rel="set_13" >
				<img title="Verbs used by David Cameron" alt="Verbs used by David Cameron" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_cameron_verbs.png" width="64" height="41" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-139" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/clegg_verbs.png" title="Verbs used by Nick Clegg in the first debate" class="thickbox" rel="set_13" >
				<img title="Verbs used by Nick Clegg" alt="Verbs used by Nick Clegg" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_clegg_verbs.png" width="64" height="42" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-134" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/brown_adj.png" title="Adjectives and Adverbs used by Gordon Brown in the first debate" class="thickbox" rel="set_13" >
				<img title="Adjectives and Adverbs used by Gordon Brown" alt="Adjectives and Adverbs used by Gordon Brown" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_brown_adj.png" width="64" height="40" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-136" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/cameron_adj.png" title="Adjectives and Adverbs used by David Cameron  in the first debate" class="thickbox" rel="set_13" >
				<img title="Adjectives and Adverbs used by David Cameron" alt="Adjectives and Adverbs used by David Cameron" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_cameron_adj.png" width="64" height="42" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-138" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/debates/clegg_adj.png" title="Adjectives and Adverbs used by Nick Clegg in the first debate" class="thickbox" rel="set_13" >
				<img title="Adjectives and Adverbs used by Nick Clegg" alt="Adjectives and Adverbs used by Nick Clegg" src="http://www.planetmarshall.co.uk/wp-content/gallery/debates/thumbs/thumbs_clegg_adj.png" width="64" height="42" />
			</a>
		</div>
	</div>
	 	 	
	<!-- Pagination -->
 	<div class="ngg-clear"></div> 	
</div>


]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2010/04/visualizing-the-prime-ministerial-debates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Near Infra Red Pseudocolour using LAB Colour Separations</title>
		<link>http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/</link>
		<comments>http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 03:08:55 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Imaging]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Photography]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=705</guid>
		<description><![CDATA[
As 2010 is the 100th anniversary of the first published infra red photograph, I thought I&#8217;d try my hand using my own digital camera and some easily acquired accessories. If you want, you can skip the theory and go straight to the description of the method and a script for Photoshop.
A quick overview of IR [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/clare_lab.jpg" title="At the back of Clare College" class="thickbox" rel="singlepic124" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/124__120x_clare_lab.jpg" alt="At the back of Clare College" title="At the back of Clare College" />
</a>

<p class="pm_first">As 2010 is the <a title="BBC article on the history of Infra Red photography" href="http://www.bbc.co.uk/blogs/photoblog/2010/01/on_a_different_wavelength_100_years_of_infrared_ph.html" target="_blank">100th anniversary of the first published infra red photograph</a>, I thought I&#8217;d try my hand using my own digital camera and some easily acquired accessories. If you want, you can <a href="http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/#method">skip</a> the theory and go straight to the description of the method and a script for Photoshop.</p>
<h3>A quick overview of IR photography</h3>
<p>The <a title="Wikipedia's entry on the Charge-Coupled Device" href="http://en.wikipedia.org/wiki/Charge-coupled_device" target="_blank">CCD</a> that is responsible for recording the images photographed by most digital cameras, is already sensitive to the near infra red part of the spectrum. That is, the part of the spectrum outside of the range visible to the human eye, but not so far as that used for, for example, thermal imaging. Since most photographers are not interested in light that they can&#8217;t see, this light is usually filtered out by an infra red <em>cutoff </em>filter placed inside the camera body, directly in front of the CCD. However, such filters are imperfect, so with some camera models by 
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/filters.png" title="CCD spectrum response" class="thickbox" rel="singlepic120" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/120__120x_filters.png" alt="CCD spectrum response" title="CCD spectrum response" />
</a>
 combining a long exposure with an infra red <em>transmitting </em>filter placed in front of the lens, some of that IR light can be recovered. The figure shows the basic principle, though I should add that the graphs are just a sketch to illustrate the principle and don&#8217;t represent an actual CCD response curve.</p>
<p><span id="more-705"></span></p>
<h3>Pseudocolour</h3>

<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/irgreyscale.jpg" title="A greyscale representation of a Near Infra Red image" class="thickbox" rel="singlepic129" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/129__120x_irgreyscale.jpg" alt="A greyscale representation of a Near Infra Red image" title="A greyscale representation of a Near Infra Red image" />
</a>
Since IR light is invisible, some method is needed to represent it in terms of the colours that we can see. Typically, this is often done by simply mapping the intensities of the IR image to a greyscale, with the result being a black and white photo with a slightly surreal look. For my photographs, however, I wanted to try an alternative method.</p>
<h3>The LAB Colour Model</h3>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/lena_rgb.png" title="'Lena' with RGB colour separation" class="thickbox" rel="singlepic122" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/122__120x_lena_rgb.png" alt="'Lena' with RGB colour separation" title="'Lena' with RGB colour separation" />
</a>
The most common method of representing a colour image is by a combination of Red, Green and Blue &#8216;colour primaries&#8217;. The reason for this is simply because it then becomes relatively trivial to display an image using a video display, which also constructs an image using a combination of red, green and blue LEDs or phosphors. This is why such a model is known as a &#8216;device dependent&#8217; model. However, RGB is not the only colour model, and if you are at all familiar with Photoshop you may be aware of the LAB model.</p>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/lena_lab.png" title="'Lena' with Luminosity and Chromaticity colour separation" class="thickbox" rel="singlepic121" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/121__120x_lena_lab.png" alt="'Lena' with Luminosity and Chromaticity colour separation" title="'Lena' with Luminosity and Chromaticity colour separation" />
</a>
LAB, or <a title="Wikipedia's entry on the CIELAB colour space" href="http://en.wikipedia.org/wiki/Lab_color_space" target="_blank">CIELAB </a>to give it its full name, is a device independent model, which like RGB is composed of three components ( or channels ) but in this case only the &#8216;A&#8217; and &#8216;B&#8217; components contain colour information, whereas the &#8216;L&#8217; component contains pure luminosity information. Thus, by separating an image into LAB components it becomes possible to manipulate the luminosity and colour components of an image independently.<br />
<a name="method"></a></p>
<h3>Method and Implementation in Photoshop</h3>
<h4>Equipment</h4>
<ol>
<li>Canon G10 Digital Compact Camera</li>
<li>LA-DC58K lens adapter for same</li>
<li>Hoya R72 58mm Infra Red filter</li>
<li>Tripod</li>
<li>Photoshop ( or GIMP )</li>
</ol>
<p>The images in this post have been created from two source images, one a long exposure taken using the IR filter and the other a conventional colour image. Both images are converted into the LAB colour space, and a single image is then produced, using the Luminosity channel from the IR image and the &#8216;A&#8217; and &#8216;B&#8217; channels from the colour image. The photoshop script below will automate the process when applied to two source images, you can then manipulate the final image using the adjustment tools. You can also do much the same thing in GIMP using the Decompose/Compose features from the Colour menu, but it does not include Photoshop&#8217;s image registration or LAB colour adjustment features.</p>
<p>Download <a href="http://www.planetmarshall.co.uk/code/photoshop/ir_composite.jsx.zip">ir_composite.jsx.zip</a></p>
<p>To use the script, open the IR and corresponding colour image, and ensure that the IR image is selected. Then apply the script.</p>
<h3>Practicalities</h3>
<p>There are a number of limitations to multiple exposure photography methods such as this, especially ones which require long exposures and changes of camera equipment. It is best suited to landscape photography in good conditions where the multiple exposures can be easily aligned. If either image contains rapidly moving subjects these can ( and will ) show up as artefacts in the resulting image.</p>
<h3>Gallery</h3>
<p>
<div class="ngg-galleryoverview" id="ngg-gallery-12">


	
	<!-- Thumbnails -->
		
	<div id="ngg-image-123" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/backs.jpg" title="The back of the Cambridge colleges" class="thickbox" rel="set_12" >
				<img title="The back of the Cambridge colleges" alt="The back of the Cambridge colleges" src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_backs.jpg" width="64" height="47" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-124" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/clare_lab.jpg" title="At the back of Clare College" class="thickbox" rel="set_12" >
				<img title="At the back of Clare College" alt="At the back of Clare College" src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_clare_lab.jpg" width="64" height="52" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-125" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/clare_lb.jpg" title="At the back of Clare College. This image has had the 'a' chromaticity channel removed" class="thickbox" rel="set_12" >
				<img title="At the back of Clare College" alt="At the back of Clare College" src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_clare_lb.jpg" width="64" height="52" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-126" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/garden.jpg" title="My back garden. This was the first image I created with this method." class="thickbox" rel="set_12" >
				<img title="My back garden" alt="My back garden" src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_garden.jpg" width="64" height="60" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-127" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/kings.jpg" title="A view of the back of Kings College. This image has also had the 'a' channel removed." class="thickbox" rel="set_12" >
				<img title="A view of the back of Kings College" alt="A view of the back of Kings College" src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_kings.jpg" width="64" height="47" />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-128" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/river.jpg" title="Clare College from the River Cam." class="thickbox" rel="set_12" >
				<img title="Clare College from the River Cam." alt="Clare College from the River Cam." src="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/thumbs/thumbs_river.jpg" width="64" height="47" />
			</a>
		</div>
	</div>
	 	 	
	<!-- Pagination -->
 	<div class="ngg-clear"></div> 	
</div>


]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight and CUDA interop</title>
		<link>http://www.planetmarshall.co.uk/2010/01/silverlight-and-cuda-interop/</link>
		<comments>http://www.planetmarshall.co.uk/2010/01/silverlight-and-cuda-interop/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 02:11:58 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CUDA]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=389</guid>
		<description><![CDATA[Update &#8211; source code now available
Microsoft have recently released a beta of Silverlight 4, which has limited support for native interoperation using COM. Potentially, this example could be applied to any number of native interop scenarios, however for this example I have chosen to use Nvidia&#8217;s CUDA technology.
Disclaimer : This is an example of what [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/cuda-interop/mandrill.jpg" title="" class="thickbox" rel="singlepic78" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/78__x96_mandrill.jpg" alt="mandrill" title="mandrill" />
</a>
<br />
<em>Update &#8211; <a href="#source">source code</a> now available</em></p>
<p class="pm_first">Microsoft have recently released a beta of Silverlight 4, which has limited support for native interoperation using COM. Potentially, this example could be applied to any number of native interop scenarios, however for this example I have chosen to use Nvidia&#8217;s CUDA technology.</p>
<blockquote><p>Disclaimer : This is an example of what can be done, not necessarily, and in all likelihood, an example of how it should be done.</p></blockquote>
<h3>About CUDA</h3>
<p>Up until around 2001 PC graphics cards, though powerful, implemented a fixed function pipeline that limited use to whatever was exposed by the APIs, usually Direct3D or OpenGL. The addition of a programmable pixel pipeline led to the use of graphics cards for more general computation tasks; at first using shaders directly, followed by higher level GPU specific programming languages, such as Brook, SH, and later NVidia&#8217;s CUDA. Most of this work was, and is, documented by the <a title="GPGPU" href="http://gpgpu.org/" target="_blank">GPGPU</a> group. <a href="http://www.nvidia.com/object/cuda_home.html#" target="_blank">NVIDIA&#8217;s website</a> shows CUDA being used in a wide variety of applications but in practice it is best employed in so called &#8220;<a title="Wikipedia : Embarrassingly Parallel" href="http://en.wikipedia.org/wiki/Embarrassingly_parallel" target="_blank">embarassingly parallel</a>&#8221; problems.<br />
<span id="more-389"></span></p>
<h3>The demonstration application</h3>
<p>The demo below shows a Silverlight 4 beta application, which implements a recursive gaussian filter. Note that this is not the same algorithm provided by the sample in the CUDA SDK, but a more efficient method, which is described in detail in <a href="#young">[1]</a> for those interested. The main advantage of a filter implemented in this way is that the computation time is independent of the width of the filter.<br />
To enable CUDA interop, you&#8217;ll need a CUDA compatible graphics card. Then do the following,</p>
<ol>
<li>Install the MFC COM application (link below). The installer should register the application with COM automatically.</li>
<li>Right click on the Silverlight App and install it for running outside of the browser. The CUDA option should now be available from the Combo box.</li>
</ol>
<p>Source code : <a title="Download source code" name="source" href="http://planetmarshall.co.uk/silverlight/cuda_interop/SilverlightCudaInteropDemo.zip">SilverlightCudaInteropDemo.zip</a><br />
<a title="Install CUDA Server application" href="http://planetmarshall.co.uk/silverlight/cuda_interop/CudaServer.msi">Install MFC COM Application (5.5 Mb)</a><br />
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996be8e0')">&#x25bc;</a> Silverlight Application</div><div id="4c516996be8e0" style="display:" class="silverlightControlHost"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="520" height="580"><param name="source" value="http://www.planetmarshall.co.uk/silverlight/cuda_interop/SlCudaInteropDemo.xap"/><param name="background" value="#212121" /><!--<param name="minRuntimeVersion" value="2.0.31005.0" />--><param name="enableHtmlAccess" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;"><img src="http://storage.timheuer.com/sl4wp-ph.png" alt="Install Microsoft Silverlight" style="border-style: none; width:520px; height:580px"/></a></object><iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe></div><br />
<h3>The native component</h3>
<p>The native component takes the form of a COM Automation server, implemented as a client side MFC application.</p>
<blockquote><p>Note: Make sure you run Visual Studio with Administrator privileges, otherwise registering the automation server with COM will fail.</p></blockquote>
<p>MFC and Automation are beyond the scope of this article, but the basic process I followed was thus</p>
<ol>
<li>Create an MFC Dialog application using the Wizard. Make sure to enable Automation support</li>
<li>Add a method to the autmation interface using the add Method wizard from the Class View</li>
<li>Add a dual interface using this <a title="TN065: Dual-Interface Support for OLE Automation Servers" href="http://msdn.microsoft.com/en-us/library/4h56szat%28VS.100%29.aspx" target="_blank">Technical Note</a> from MSDN.</li>
<li>If you get link errors, make sure to include the output of MIDL in the application class ( the one that contains OnInitInstance). I couldn&#8217;t find any reference to this step, but it&#8217;s how the samples work.</li>
<li>Make sure that the run time library options passed to nvcc and msvc match, ie they should all use a DLL or Static linking, not a mixture of both</li>
<li>If you get stuck, take a look at the <a title="MFC Samples" href="http://msdn.microsoft.com/en-us/library/482ck6x8%28VS.100%29.aspx" target="_blank">MFC Samples</a>, particularly <a title="ACDUAL Sample: Adds Dual Interfaces to an Automation Application" href="http://msdn.microsoft.com/en-us/library/xfx55tf8%28VS.100%29.aspx" target="_blank">acdual</a>.</li>
</ol>
<p>when you pass a native array through COM Automation, it is converted to a <a title="Array Manipulation Functions from MSDN" href="http://msdn.microsoft.com/en-us/library/ms221145%28VS.100%29.aspx" target="_blank"><code>SAFEARRAY</code></a> on the native side. Note that I couldn&#8217;t find any documentation on this, I discovered it through experience. The code snippets below show sending and receiving array data between Silverlight and the MFC application.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996c6f0f')">&#x25ba;</a> Listing : Calling COM from Silverlight</div><div id="4c516996c6f0f" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="co1">// note that ComAutomationFactory has become AutomationFactory</span><br />
<span class="co1">// in Silverlight 4 RC</span><br />
<span class="kw4">dynamic</span> cuda <span class="sy0">=</span> AutomationFactory.<span class="me1">CreateObject</span><span class="br0">&#40;</span><span class="st0">&quot;CudaServer.Application&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw4">float</span><span class="br0">&#91;</span><span class="br0">&#93;</span> data <span class="sy0">=</span> <span class="kw3">new</span> <span class="br0">&#91;</span><span class="br0">&#93;</span> <span class="br0">&#123;</span>1.0f, 3.14f <span class="br0">&#125;</span><span class="sy0">;</span><br />
<span class="kw4">dynamic</span> retData <span class="sy0">=</span> cuda.<span class="me1">Process</span><span class="br0">&#40;</span> data <span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="co1">// retData is a managed float array</span></div></div></div>


<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996c98f4')">&#x25ba;</a> Listing : Returning data to Silverlight from MFC via COM</div><div id="4c516996c98f4" style="display:none;" class="code"><div class="cpp pm_syntax">VARIANT CCudaServer<span class="sy4">::</span><span class="me2">Process</span><span class="br0">&#40;</span>VARIANT <span class="sy3">&amp;</span>amp<span class="sy4">;</span>data<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; SAFEARRAY <span class="sy2">*</span>pSrcData <span class="sy1">=</span> &nbsp;data.<span class="me1">parray</span><span class="sy4">;</span><br />
<br />
&nbsp; <span class="co1">// this will copy the safe array into the variant</span><br />
&nbsp; CComVariant var<span class="br0">&#40;</span>pSrcData<span class="br0">&#41;</span><span class="sy4">;</span><br />
<br />
&nbsp; <span class="co1">// when we return the VARIANT containing the SAFEARRAY</span><br />
&nbsp; <span class="co1">// it will be marshaled to Silverlight as a managed array</span><br />
&nbsp; VARIANT retVal<span class="sy4">;</span><br />
&nbsp; VariantInit<span class="br0">&#40;</span> <span class="sy3">&amp;</span>amp<span class="sy4">;</span>retVal <span class="br0">&#41;</span><span class="sy4">;</span><br />
&nbsp; var.<span class="me1">Detach</span><span class="br0">&#40;</span> <span class="sy3">&amp;</span>amp<span class="sy4">;</span>retVal <span class="br0">&#41;</span><span class="sy4">;</span><br />
&nbsp; retVal.<span class="me1">vt</span> <span class="sy1">=</span> VT_ARRAY <span class="sy3">|</span> VT_R4<span class="sy4">;</span><br />
&nbsp; <span class="kw1">return</span> retVal<span class="sy4">;</span><br />
<span class="br0">&#125;</span></div></div></div>

<h3>Using MEF to implement the application</h3>
<p>The <a title="Managed Extensibility Framework at Codeplex" href="http://www.codeplex.com/MEF" target="_blank">Managed Extensibility Framework</a> is an extensible plugin framework for .NET applications and Silverlight. I have used it to dynamically discover implementations of <code>IProcessorProvider</code> based on the permissions available to the Silverlight application. The figure below shows the component structure of the application.</p>

<!-- collapsible header -->

<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996c5d5c')">&#x25ba;</a> Figure : Component diagram for demo application</div>
<div id="4c516996c5d5c" style="display:none;">
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/cuda-interop/slcuda_component.png" title="Component diagram for demo application" class="thickbox" rel="singlepic77" >
	<img class="ngg-singlepic" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/77__475x_slcuda_component.png" alt="slcuda_component" title="slcuda_component" />
</a>
</div>

<h3>Performance notes</h3>
<h4>Silverlight</h4>
<p>Unlike the <a title="My Reaction-Diffusion simulator" href="http://www.planetmarshall.co.uk/index.php/2009/03/reaction-diffusion-models/">Reaction Diffusion simulation</a>, for this application I have chosen to use Silverlight&#8217;s <a title="WirteableBitmap in Silverlight 3, from MSDN" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28VS.95%29.aspx" target="_blank"><code>WriteableBitmap</code></a>, introduced in Silverlight 3, rather than <a title="Joe Stegman's PNG Encoder for Silverlight" href="http://blogs.msdn.com/jstegman/archive/2008/04/21/dynamic-image-generation-in-silverlight.aspx" target="_blank">dynamic PNG encoding</a>. This revealed an interesting performance issue when using a typical double loop to iterate over the pixels. Initial timings revealed that the vast majority of the time was spent in updating the <code>WriteableBitmap</code> rather than actually performing the image processing. The initial update loop used the <code>PixelWidth</code> and <code>PixelHeight</code> properties to bound the loop counters, taking about 200ms to iterate over the loop.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996cd3a4')">&#x25ba;</a> Listing : Updating bitmap using property accessors</div><div id="4c516996cd3a4" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> j <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> j <span class="sy0">&amp;</span>lt<span class="sy0">;</span> bmp.<span class="me1">PixelHeight</span><span class="sy0">;</span> <span class="sy0">++</span>j<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&amp;</span>lt<span class="sy0">;</span> bmp.<span class="me1">PixelWidth</span><span class="sy0">;</span> <span class="sy0">++</span>i<span class="br0">&#41;</span><br />
&nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp;<span class="co1">// update pixels</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>By caching the bitmap properties in local variables, the timing was reduced to ~5ms. Needless to say I was shocked by how much of a difference such a seemingly trivial change made.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996cfb0a')">&#x25ba;</a> Listing : Updating bitmap with cached variables</div><div id="4c516996cfb0a" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw4">int</span> pxWidth <span class="sy0">=</span>  bmp.<span class="me1">PixelWidth</span><span class="sy0">;</span><br />
<span class="kw4">int</span> pxHeight <span class="sy0">=</span> bmp.<span class="me1">PixelHeight</span><span class="sy0">;</span><br />
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> j <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> j <span class="sy0">&amp;</span>lt<span class="sy0">;</span> pxHeight<span class="sy0">;</span> <span class="sy0">++</span>j<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&amp;</span>lt<span class="sy0">;</span> pxWidth<span class="sy0">;</span> <span class="sy0">++</span>i<span class="br0">&#41;</span><br />
&nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp;<span class="co1">// update pixels</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<h4>OLE Automation</h4>
<p>The guidelines for building performant automation code is much the same as that for other unmanaged interop scenarios in .NET : avoid chatty interfaces. Note that this is exactly what I have not done here. In fact, the time it takes CUDA to perform the image processing is dwarfed by the time it takes to marshal the data between Silverlight and COM. This can be mitigated somewhat by splitting the blur call into two operations, one to load the image, which is called only upon initialization, and one to perform the blur.</p>
<h4>CUDA</h4>
<p>CUDA operations are extremely sensitive to data alignment and the order in which threads access data. Kernels should be written in such a way that threads access adjacent data elements, meaning that the row major access pattern familiar to C and C# developers would produce suboptimal performance ( sometimes by as much as an order of magnitude ). Instead, array accesses should be performed in a manner more reminiscent of FORTRAN. In addition, 2D arrays should be padded out so that threads access data elements that are correctly aligned ( see the CUDA documentation for the correct alignment values ). A full exposition of performance optimization for CUDA is really beyond the scope of this article, there are many examples in the <a title="Learn More about CUDA - NVIDIA" href="http://www.nvidia.com/object/cuda_education.html" target="_blank">NVIDIA documentation</a> although the terminology can be somewhat opaque. One of the clearest explanations I have found is this <a title="Supercomputing 2007 CUDA Tutorial" href="http://gpgpu.org/sc2007" target="_blank">presentation </a>from Mark Harris at Supercomputing 2007.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996d245b')">&#x25ba;</a> Listing : Row major access pattern</div><div id="4c516996d245b" style="display:none;" class="code"><div class="cuda pm_syntax"><span class="kw2">__global__</span> <span class="kw4">void</span> kernel<span class="br0">&#40;</span> <span class="kw4">float</span> <span class="sy0">*</span>destData<span class="sy0">,</span> <span class="kw4">float</span> <span class="sy0">*</span>srcData<span class="sy0">,</span> <span class="kw4">int</span> stride<span class="sy0">,</span> <span class="kw4">int</span> height <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; <span class="co1">// suboptimal access. Each thread accesses elements</span><br />
&nbsp;<span class="co1">// in a striding pattern</span><br />
&nbsp; <span class="kw4">int</span> rowStart <span class="sy0">=</span> <span class="br0">&#40;</span><span class="kw3">blockDim</span>.<span class="me1">x</span><span class="sy0">*</span><span class="kw3">blockIdx</span>.<span class="me1">x</span><span class="sy0">+</span><span class="kw3">threadIdx</span>.<span class="me1">x</span><span class="br0">&#41;</span><span class="sy0">*</span>stride<span class="sy0">;</span><br />
&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span> <span class="kw4">int</span> i <span class="sy0">=</span> rowStart<span class="sy0">;</span> i <span class="sy0">&lt;</span> rowStart<span class="sy0">+</span>stride<span class="sy0">;</span> <span class="sy0">++</span>i <span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; destData<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> srcData<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>


<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516996d3f7e')">&#x25ba;</a> Listing : Column major access patern</div><div id="4c516996d3f7e" style="display:none;" class="code"><div class="cuda pm_syntax"><span class="kw2">__global__</span> <span class="kw4">void</span> kernel<span class="br0">&#40;</span> <span class="kw4">float</span> <span class="sy0">*</span>destData<span class="sy0">,</span> <span class="kw4">float</span> <span class="sy0">*</span>srcData<span class="sy0">,</span> <span class="kw4">int</span> stride<span class="sy0">,</span> <span class="kw4">int</span> height <span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; <span class="co1">// optimal access pattern, each thread accesses adjacent elements</span><br />
&nbsp; <span class="kw4">int</span> colStart <span class="sy0">=</span> <span class="kw3">blockDim</span>.<span class="me1">x</span><span class="sy0">*</span><span class="kw3">blockIdx</span>.<span class="me1">x</span><span class="sy0">+</span><span class="kw3">threadIdx</span>.<span class="me1">x</span><span class="sy0">;</span><br />
&nbsp; <span class="co1">// this case, 16*sizeof(float)= 64 bytes</span><br />
&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span> <span class="kw4">int</span> i <span class="sy0">=</span> colStart <span class="sy0">;</span> i <span class="sy0">&lt;</span> colStart<span class="sy0">+</span><span class="br0">&#40;</span>stride<span class="sy0">*</span>height<span class="br0">&#41;</span><span class="sy0">;</span> i<span class="sy0">+=</span>stride <span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; destData<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> srcData<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<h3>References</h3>
<ol>
<li><span class="p1"><a name="young"></a>Young, I.T. &amp; van Vliet,L.J, 1995. <a title="Recursive Implementation of the Gaussian Filter" href="http://www.sciencedirect.com/science?_ob=ArticleURL&amp;_udi=B6V18-3YS90HC-D&amp;_user=10&amp;_coverDate=06%2F30%2F1995&amp;_rdoc=2&amp;_fmt=high&amp;_orig=browse&amp;_srch=doc-info%28%23toc%235668%231995%23999559997%23172292%23FLP%23display%23Volume%29&amp;_cdi=5668&amp;_sort=d&amp;_docanchor=&amp;_ct=11&amp;_acct=C000050221&amp;_version=1&amp;_urlVersion=0&amp;_userid=10&amp;md5=cdfad44c178fc20739d26562c5f26e04" target="_blank">Recursive implementation of the Gaussian filter</a>. <em>Signal Processing</em>, 44, pp.139-151. </span></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2010/01/silverlight-and-cuda-interop/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Searching MSDN Using Google</title>
		<link>http://www.planetmarshall.co.uk/2009/11/searching-msdn-using-google/</link>
		<comments>http://www.planetmarshall.co.uk/2009/11/searching-msdn-using-google/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 15:40:29 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=382</guid>
		<description><![CDATA[I sometimes find it useful to search MSDN directly using Google, so I wrote a search plugin using OpenSearch to make this easier. Firefox should discover the search plugin automatically &#8211; it should appear in the search drop down at the top right. Otherwise, you can just install the plugin directly. For more details, see [...]]]></description>
			<content:encoded><![CDATA[<p class="pm_first"><span>I</span> sometimes find it useful to search MSDN directly using Google, so I wrote a search plugin using OpenSearch to make this easier. Firefox should discover the search plugin automatically &#8211; it should appear in the search drop down at the top right. Otherwise, you can just <a href="javascript:window.external.AddSearchProvider('http://www.planetmarshall.co.uk/code/google_msdn.xml')">install</a> the plugin directly. For more details, see <a href="https://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox" target="_new">Creating OpenSearch plugins for Firefox.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2009/11/searching-msdn-using-google/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Merged ResourceDictionaries in Silverlight Themes</title>
		<link>http://www.planetmarshall.co.uk/2009/07/using-merged-resourcedictionaries-in-silverlight-themes/</link>
		<comments>http://www.planetmarshall.co.uk/2009/07/using-merged-resourcedictionaries-in-silverlight-themes/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 02:16:59 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=303</guid>
		<description><![CDATA[Silverlight 3.0 moved its featureset closer to that of WPF by adding support for merged Resource Dictionaries and Style Inheritance. Without these features, developing custom templates and styles for Silverlight controls can become a bit of a copy-and-paste nightmare. Since I have used the implicit theming feature built into the Silverlight Toolkit to make my [...]]]></description>
			<content:encoded><![CDATA[<p class="pm_first"><span>S</span>ilverlight 3.0 moved its featureset closer to that of WPF by adding support for merged <a href="http://msdn.microsoft.com/en-us/library/cc903952%28VS.95%29.aspx" target="_new">Resource Dictionaries</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.style.basedon%28VS.95%29.aspx" target="_new">Style Inheritance</a>. Without these features, developing custom templates and styles for Silverlight controls can become a bit of a copy-and-paste nightmare. Since I have used the implicit theming feature built into the <a href="http://www.codeplex.com/Silverlight" target="_new">Silverlight Toolkit</a> to make my Silverlight controls fit into the overall look and feel of this site, I was hoping that these features would enable me to refactor my themes developed for Silverlight 2.0 to be a bit less unwieldy.</p>
<p><span id="more-303"></span></p>
<h3>Silverlight toolkit themes do not support merged dictionaries</h3>
<p>Unfortunately, merged dictionaries are not supported by the Silverlight Toolkit&#8217;s Themes feature &#8211; at least not as it stands. For example, the following XAML and accompanying class causes a <code>XamlParseException</code> if you try to use it.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699701caf')">&#x25ba;</a> Listing : </div><div id="4c51699701caf" style="display:none;" class="code"><div class="xml pm_syntax"><span class="sc3"><span class="re1">&lt;ResourceDictionary<span class="re2">&gt;</span></span></span><br />
&nbsp;<span class="sc3"><span class="re1">&lt;ResourceDictionary.MergedDictionaries<span class="re2">&gt;</span></span></span><br />
&nbsp; <span class="sc3"><span class="re1">&lt;ResourceDictionary</span> <span class="re0">Source</span>=<span class="st0">&quot;/MergedTheme;component/Styles/Button.xaml&quot;</span><span class="re2">/&gt;</span></span><br />
&nbsp;<span class="sc3"><span class="re1">&lt;ResourceDictionary.MergedDictionaries<span class="re2">&gt;</span></span></span><br />
<span class="sc3"><span class="re1">&lt;/ResourceDictionary<span class="re2">&gt;</span></span></span></div></div></div>


<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699702b3b')">&#x25ba;</a> Listing : </div><div id="4c51699702b3b" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">public</span> <span class="kw4">class</span> MergedTheme <span class="sy0">:</span> Theme <span class="br0">&#123;</span><br />
&nbsp;<span class="kw1">public</span> MergedTheme<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">:</span> <br />
&nbsp; <span class="kw1">base</span><span class="br0">&#40;</span><span class="kw3">typeof</span><span class="br0">&#40;</span>MergedTheme<span class="br0">&#41;</span>.<span class="me1">Assembly</span>, <span class="st0">&quot;MergedTheme.Theme.xaml&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; DefaultStyleKey <span class="sy0">=</span> <span class="kw3">typeof</span><span class="br0">&#40;</span>MergedTheme<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>All is not lost however, since full source code is provided for the Silverlight Toolkit, so it becomes a straightforward matter to track down the problem and supply a patch. </p>
<h3>Writing a test to reproduce the problem</h3>
<p>Since the toolkit comes with an accompanying test suite, we proceed in textbook <a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_new">TDD</a> fashion by first writing a test that exercises the issue. We can reuse some of the existing code to do this, adding a resource dictionary containing a merged dictionary reference and adding the following test to the <code>ImplicitStyleManagerTest</code> class</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699705195')">&#x25ba;</a> Listing : </div><div id="4c51699705195" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="co1">/// &lt;summary&gt;</span><br />
<span class="co1">/// Test that styles contained in a &nbsp;merged dictionary can be successfully applied</span><br />
<span class="co1">/// &lt;/summary&gt;</span><br />
<span class="br0">&#91;</span>TestMethod<span class="br0">&#93;</span><br />
<span class="br0">&#91;</span>Asynchronous<span class="br0">&#93;</span><br />
<span class="br0">&#91;</span>Description<span class="br0">&#40;</span><span class="st0">&quot;Test that a dictionary contining merged dictionaries can be successfully loaded.&quot;</span><span class="br0">&#41;</span><span class="br0">&#93;</span><br />
<span class="kw1">public</span> <span class="kw1">void</span> TestResourceDictionaryWithMergedDictionaries<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp;Uri uri <span class="sy0">=</span> <span class="kw3">new</span> Uri<span class="br0">&#40;</span><span class="st0">&quot;System.Windows.Controls.Testing.Theming;<br />
&nbsp; component/ImplicitStyleManager/MergedResourceDictionary.xaml&quot;</span>, UriKind.<span class="me1">Relative</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp;TestAuto<span class="br0">&#40;</span> <span class="br0">&#40;</span>stackPanel<span class="br0">&#41;</span> <span class="sy0">=&gt;</span> <span class="br0">&#123;</span><br />
&nbsp; SetResourceDictionaryUri<span class="br0">&#40;</span>stackPanel, uri<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; ImplicitStyleManager.<span class="me1">SetApplyMode</span><span class="br0">&#40;</span>stackPanel, ImplicitStylesApplyMode.<span class="kw1">Auto</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; <span class="br0">&#125;</span>, Colors.<span class="me1">Blue</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>The test fails as we would expect.</p>

<!-- collapsible header -->

<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996f0b02')">&#x25ba;</a> Figure : The test written to exercise the bug fails as expected.</div>
<div id="4c516996f0b02" style="display:none;">
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/sltoolkit/testfail.png" title="The test written to exercise the bug fails as expected." class="thickbox" rel="singlepic70" >
	<img class="ngg-singlepic" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/70__x_testfail.png" alt="Failing unit test" title="Failing unit test" />
</a>
</div>

<h3>Fix the code to make the test pass</h3>
<p>The Theme class works by transforming the<code> ResourceDictionary</code> xaml into a <code>ContentControl</code>. A quick glance at the xaml generated by this process in the Visual Studio debugger shows why an exception is being raised.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c516997081f7')">&#x25ba;</a> Listing : </div><div id="4c516997081f7" style="display:none;" class="code"><div class="xml pm_syntax"><span class="sc3"><span class="re1">&lt;ContentControl<span class="re2">&gt;</span></span></span><br />
&nbsp;<span class="sc3"><span class="re1">&lt;ContentControl.Resources<span class="re2">&gt;</span></span></span><br />
&nbsp; <span class="sc3"><span class="re1">&lt;ResourceDictionary.MergedDictionaries<span class="re2">&gt;</span></span></span><br />
&nbsp; &nbsp;<span class="sc3"><span class="re1">&lt;ResourceDictionary</span> <span class="re0">Source</span>=<span class="st0">&quot;[...]/ResourceDictionaryForMerge.xaml&quot;</span> <span class="re2">/&gt;</span></span> <br />
&nbsp; <span class="sc3"><span class="re1">&lt;/ResourceDictionary.MergedDictionaries<span class="re2">&gt;</span></span></span><br />
&nbsp;<span class="sc3"><span class="re1">&lt;/ContentControl.Resources<span class="re2">&gt;</span></span></span><br />
<span class="sc3"><span class="re1">&lt;/ContentControl<span class="re2">&gt;</span></span></span></div></div></div>

<p>The <code>ResourceDictionary.MergedDictionaries</code> element is missing its parent <code>ResourceDictionary</code> element, so we add a couple of lines of code to ResourceParser.ParseElement to detect the element and wrap it in a <code>ResourceDictionary</code>, using LINQ to XML.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699709164')">&#x25ba;</a> Listing : </div><div id="4c51699709164" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">private</span> <span class="kw1">static</span> <span class="kw1">void</span> ParseElement<span class="br0">&#40;</span>XmlReader reader, XmlWriter writer, <span class="kw4">bool</span> checkTypes<span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>reader.<span class="me1">Depth</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>...<span class="br0">&#125;</span><br />
&nbsp;<span class="kw1">else</span> <span class="br0">&#123;</span><br />
&nbsp; <span class="co1">// handle merged dictionaries by wrapping them in a ResourceDictionary element</span><br />
&nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span>reader.<span class="me1">Name</span> <span class="sy0">==</span> <span class="st0">&quot;ResourceDictionary.MergedDictionaries&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp;XElement parent <span class="sy0">=</span> <span class="kw3">new</span> XElement<span class="br0">&#40;</span><span class="st0">&quot;ResourceDictionary&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp;parent.<span class="me1">Add</span><span class="br0">&#40;</span>XElement.<span class="me1">ReadFrom</span><span class="br0">&#40;</span>reader<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp;writer.<span class="me1">WriteRaw</span><span class="br0">&#40;</span>parent.<span class="me1">ToString</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; <span class="br0">&#125;</span><br />
&nbsp; <span class="kw1">else</span> <span class="br0">&#123;</span> ... <span class="br0">&#125;</span><br />
&nbsp;<span class="br0">&#125;</span> &nbsp; <br />
<span class="br0">&#125;</span></div></div></div>

<p>Having made the change, we rerun the test.</p>

<!-- collapsible header -->

<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516996f3300')">&#x25ba;</a> Figure : How I love the green bar</div>
<div id="4c516996f3300" style="display:none;">
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/sltoolkit/testpass.png" title="How I love the green bar" class="thickbox" rel="singlepic71" >
	<img class="ngg-singlepic" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/71__x_testpass.png" alt="How I love the green bar" title="How I love the green bar" />
</a>
</div>

<p>As we would hope, our custom theme now works as expected and we also have a unit test that ensures the bug does not reoccur. Note the Xaml code above, in that the Resource Dictionary is referenced using <a href="http://msdn.microsoft.com/en-us/library/aa970069.aspx" target="_new">Pack Uri</a> syntax. This is because <code>Button.xaml</code> is compiled as a Resource, rather than Content, since the latter doesn&#8217;t appear to work reliably and can result in obfuscated error messages such as <i>XamlParseException: attribute &#8220;Button.xaml&#8221; value out of range.</i></p>

<!-- collapsible header -->

<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c51699701691')">&#x25ba;</a> Figure : The button on the right gets its theme from a merged ResourceDictionary</div>
<div id="4c51699701691" style="display:none;">
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/sltoolkit/themed.png" title="The button on the right gets its theme from a merged ResourceDictionary" class="thickbox" rel="singlepic72" >
	<img class="ngg-singlepic" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/72__x_themed.png" alt="Themed controls" title="Themed controls" />
</a>
</div>

<p>I have submitted the patch for this fix to the toolkit site on Codeplex.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2009/07/using-merged-resourcedictionaries-in-silverlight-themes/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Implementation of the Reaction Diffusion Simulation</title>
		<link>http://www.planetmarshall.co.uk/2009/04/implentation-of-the-reaction-diffusion-simulation/</link>
		<comments>http://www.planetmarshall.co.uk/2009/04/implentation-of-the-reaction-diffusion-simulation/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 09:34:08 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=111</guid>
		<description><![CDATA[Update &#8211; This post was written before the release of Silverlight 3.0b, which provides a number of enhancements relevant to this implementation, such as a WriteableBitmap and Pixel Shaders
Rendering
The first obstacle to implementing the RD simulation is that Silverlight 2.0 does not by default provide a means of generating dynamic images. WPF has a WriteableBitmap, [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/blood.png" title="" class="thickbox" rel="singlepic65" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/65__x96_blood.png" alt="blood.png" title="blood.png" />
</a>
<em>Update &#8211; This post was written before the release of <a href="http://silverlight.net/getstarted/silverlight3/default.aspx" target="_new">Silverlight 3.0b</a>, which provides a number of enhancements relevant to this implementation, such as a WriteableBitmap and Pixel Shaders</em></p>
<h3>Rendering</h3>
<p>The first obstacle to implementing the <a href="http://www.planetmarshall.co.uk/index.php/2009/03/reaction-diffusion-models/">RD simulation</a> is that Silverlight 2.0 does not by default provide a means of generating dynamic images. WPF has a WriteableBitmap, but no equivalent exists in Silverlight. However, it does support PNG streams so we can dynamically update a bitmap by encoding it to PNG on the fly. For this I have used <a href="http://blogs.msdn.com/jstegman/default.aspx">Joe Stegman&#8217;s</a> <a href="http://blogs.msdn.com/jstegman/archive/2008/10/27/silverlight-2-sample-updates.aspx">PNGEncoder </a>class, which I have modified slightly to deal with RGB data and to reduce memory usage.<br />
<span id="more-111"></span></p>
<h3>Performance notes</h3>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/waves.png" title="" class="thickbox" rel="singlepic69" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/69__x96_waves.png" alt="waves.png" title="waves.png" />
</a>
Performance of the simulator is dominated by the time it takes to update the arrays containing the concentration values of the chemicals. Actual rendering time is negligible, even though the image has to be dynamically encoded to a PNG file in order for Silverlight to display it. There are two ways of implementing 2D arrays in Silverlight with C#, rectangular arrays or C style jagged arrays. If this were a desktop application, the most performant method would be to use rectangular arrays and unsafe access, however that option is not available to us in Silverlight so it turns out that, for safe access, jagged arrays are faster.</p>
<p>For example, originally the simulation step looked like this</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699729890')">&#x25ba;</a> Listing : Rectangular array implementation</div><div id="4c51699729890" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> j <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> j <span class="sy0">&amp;</span>lt<span class="sy0">;</span> H<span class="sy0">;</span> j<span class="sy0">++</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp;<span class="kw4">int</span> jm <span class="sy0">=</span> j <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> j <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> H <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">int</span> jp <span class="sy0">=</span> j <span class="sy0">!=</span> H <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> j <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&amp;</span>lt<span class="sy0">;</span> W<span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span><br />
&nbsp;<span class="br0">&#123;</span><br />
&nbsp; <span class="kw4">int</span> im <span class="sy0">=</span> i <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> i <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> W <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">int</span> ip <span class="sy0">=</span> i <span class="sy0">!=</span> W <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> i <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2u <span class="sy0">=</span> U<span class="br0">&#91;</span>j,im<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>j,ip<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>jm,i<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>jp,i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>U<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2v <span class="sy0">=</span> V<span class="br0">&#91;</span>j,im<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>j,ip<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>jm,i<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>jp,i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> uv2 <span class="sy0">=</span> U<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; Uu<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span> <span class="sy0">=</span> du<span class="sy0">*</span>d2u<span class="sy0">-</span>uv2<span class="sy0">+</span>F<span class="sy0">+</span>U<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F<span class="sy0">;</span><br />
&nbsp; Vv<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span> <span class="sy0">=</span> dv<span class="sy0">*</span>d2v<span class="sy0">+</span>uv2<span class="sy0">+</span>V<span class="br0">&#91;</span>j,i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F_minus_k<span class="sy0">;</span><br />
&nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>On my machine this took on the order of 600ms to perform 100 iterations. Using jagged arrays instead, we have the following</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c5169972d79c')">&#x25ba;</a> Listing : Jagged array implementation</div><div id="4c5169972d79c" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> j <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> j <span class="sy0">&amp;</span>lt<span class="sy0">;</span> H<span class="sy0">;</span> j<span class="sy0">++</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp;<span class="kw4">int</span> jm <span class="sy0">=</span> j <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> j <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> H <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">int</span> jp <span class="sy0">=</span> j <span class="sy0">!=</span> H <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> j <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&amp;</span>lt<span class="sy0">;</span> W<span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span><br />
&nbsp;<span class="br0">&#123;</span><br />
&nbsp; <span class="kw4">int</span> im <span class="sy0">=</span> i <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> i <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> W <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">int</span> ip <span class="sy0">=</span> i <span class="sy0">!=</span> W <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> i <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2u <span class="sy0">=</span> U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>im<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>ip<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>jm<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">+</span>U<span class="br0">&#91;</span>jp<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2v <span class="sy0">=</span> V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>im<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>ip<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>jm<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">+</span>V<span class="br0">&#91;</span>jp<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> uv2 <span class="sy0">=</span> U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; Uu<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> du<span class="sy0">*</span>d2u<span class="sy0">-</span>uv2<span class="sy0">+</span> F<span class="sy0">+</span>U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F<span class="sy0">;</span><br />
&nbsp; Vv<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> dv<span class="sy0">*</span>d2v<span class="sy0">+</span>uv2<span class="sy0">+</span>V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F_minus_k<span class="sy0">;</span><br />
&nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>Just replacing the array type and making no other changes this now takes about 500ms, an improvement of about 13%. However, now that we are using jagged arrays we can do better and move the row accesses out of the inner loop.</p>

<div class="wp_syntax">
<div class="wp_header"><a onclick="pm_toggleCodeBlock(this,'4c51699731a12')">&#x25ba;</a> Listing : Jagged array with outer loop caching</div><div id="4c51699731a12" style="display:none;" class="code"><div class="csharp pm_syntax"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> j <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> j <span class="sy0">&amp;</span>lt<span class="sy0">;</span> H<span class="sy0">;</span> j<span class="sy0">++</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp;<span class="kw4">int</span> jm <span class="sy0">=</span> j <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> j <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> H <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">int</span> jp <span class="sy0">=</span> j <span class="sy0">!=</span> H <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> j <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> u_m <span class="sy0">=</span> U<span class="br0">&#91;</span>jm<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> u <span class="sy0">=</span> U<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> u_p <span class="sy0">=</span> U<span class="br0">&#91;</span>jp<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> v_m <span class="sy0">=</span> V<span class="br0">&#91;</span>jm<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> v <span class="sy0">=</span> V<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> v_p <span class="sy0">=</span> V<span class="br0">&#91;</span>jp<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> uu <span class="sy0">=</span> Uu<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw4">var</span> vv <span class="sy0">=</span> Vv<span class="br0">&#91;</span>j<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&amp;</span>lt<span class="sy0">;</span> W<span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span><br />
&nbsp;<span class="br0">&#123;</span><br />
&nbsp; <span class="kw4">int</span> im <span class="sy0">=</span> i <span class="sy0">!=</span> <span class="nu0">0</span> <span class="sy0">?</span> i <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">:</span> W <span class="sy0">-</span> <span class="nu0">1</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">int</span> ip <span class="sy0">=</span> i <span class="sy0">!=</span> W <span class="sy0">-</span> <span class="nu0">1</span> <span class="sy0">?</span> i <span class="sy0">+</span> <span class="nu0">1</span> <span class="sy0">:</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2u <span class="sy0">=</span> u<span class="br0">&#91;</span>im<span class="br0">&#93;</span><span class="sy0">+</span>u<span class="br0">&#91;</span>ip<span class="br0">&#93;</span><span class="sy0">+</span>u_m<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">+</span>u_p<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>u<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> d2v <span class="sy0">=</span> v<span class="br0">&#91;</span>im<span class="br0">&#93;</span><span class="sy0">+</span>v<span class="br0">&#91;</span>ip<span class="br0">&#93;</span><span class="sy0">+</span>v_m<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">+</span>v_p<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">-</span><span class="nu0">4</span><span class="sy0">*</span>v<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; <span class="kw4">double</span> uv2 <span class="sy0">=</span> u<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>v<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">*</span>v<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">;</span><br />
&nbsp; uu<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> du<span class="sy0">*</span>d2u<span class="sy0">-</span>uv2<span class="sy0">+</span>F<span class="sy0">+</span>u<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F<span class="sy0">;</span><br />
&nbsp; vv<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> dv<span class="sy0">*</span>d2v<span class="sy0">+</span>uv2<span class="sy0">+</span>v<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="sy0">*</span>one_minus_F_minus_k<span class="sy0">;</span><br />
&nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div></div></div>

<p>This brings the count down to about 330ms, an improvement of about 40% over the original implementation.</p>
<p>We&#8217;ve taken the sequential code about as far as we can go. The next step is to try to take advantage of muliple cores that may be available on the user&#8217;s machine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2009/04/implentation-of-the-reaction-diffusion-simulation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Reaction-Diffusion Models</title>
		<link>http://www.planetmarshall.co.uk/2009/03/reaction-diffusion-models/</link>
		<comments>http://www.planetmarshall.co.uk/2009/03/reaction-diffusion-models/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 00:27:03 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Differential Equations]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=124</guid>
		<description><![CDATA[One of Alan Turing&#8217;s many contributions to mathematics and science during the 20th century was his 1952 paper on &#8220;The Chemical Basis of Morphogenesis&#8221; in which he suggested that a simple model of coupled differential equations could account for pattern formation in natural processes such as those found on animal coats. Such models are known [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/maze.png" title="" class="thickbox" rel="singlepic68" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/68__x96_maze.png" alt="maze.png" title="maze.png" />
</a>

<p class="pm_first"><span>O</span>ne of <a target="_new" href="http://en.wikipedia.org/wiki/Alan_Turing">Alan Turing</a>&#8217;s many contributions to mathematics and science during the 20th century was his <a href="#1_turing">1952 paper</a> on &#8220;The Chemical Basis of Morphogenesis&#8221; in which he suggested that a simple model of coupled differential equations could account for pattern formation in natural processes such as those found on animal coats. Such models are known as Reaction-Diffusion models, and take the following general form<br />
<center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_7a2bc8ea1910cfbd65cd8f6e0f9d93db.png" align="absmiddle" class="tex" alt="\frac{\partial}{\partial t}\mathbf{q}=\mathbf{D}\nabla^2\mathbf{q}+\mathbf{R}(\mathbf{q})" /></center></p>
<p><span id="more-124"></span></p>
<p>The equation describes how the concentration of each chemical components in q evolves as a function of the other components. I have chosen to illustrate the Gray-Scott model; the physical derivation of the reactant term is described in detail in <a href="#2_grayscott">[2]</a>, the addition of the diffusion term and the resultant behaviour in <a href="#3_pearson">[3]</a>. The model has two chemical components, U and V and is described as follows.<br />
<center><img src="http://www.planetmarshall.co.uk/wp-content/cache/tex_0ce40140abea7929669115d693d6b1ea.png" align="absmiddle" class="tex" alt="\begin{align*}<br />
\frac{\partial}{\partial t}U&#038;=D_u\nabla^2U-UV^2+F(1-U) \\<br />
\frac{\partial}{\partial t}V&#038;=D_v\nabla^2V+UV^2-(F+k)V<br />
\end{align*}" /></center></p>
<p>The model is what is knows as an activator-inhibitor model, in which one chemical acts to inhibit the growth of the other.</p>
<h3>Simulation</h3>
<p>The simulation is implemented with <a href="http://www.silverlight.net" target="_new">Silverlight 2.0</a>. For full details of the implementation see the separate <a href="http://www.planetmarshall.co.uk/index.php/2009/04/implentation-of-the-reaction-diffusion-simulation/">post</a>. For guidance in parameter selection, see <a href="#3_pearson">[3]</a>, or just select a preset and modify it. Note that the Png image generation feature currently requires the <a target="_new" href="http://www.mozilla.com/firefox/">Firefox</a> browser.</p>
<p><div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c516997405f2')">&#x25ba;</a> Silverlight Application</div><div id="4c516997405f2" style="display:none" class="silverlightControlHost"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="450" height="300"><param name="source" value="http://www.planetmarshall.co.uk/silverlight/ReactionDiffusion.xap"/><param name="background" value="#212121" /><!--<param name="minRuntimeVersion" value="2.0.31005.0" />--><param name="enableHtmlAccess" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;"><img src="http://storage.timheuer.com/sl4wp-ph.png" alt="Install Microsoft Silverlight" style="border-style: none; width:450px; height:300px"/></a></object><iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe></div><br />
<h3>Gallery</h3>
<div class="ngg-galleryoverview" id="ngg-gallery-5">


	
	<!-- Thumbnails -->
		
	<div id="ngg-image-65" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/blood.png" title=" " class="thickbox" rel="set_5" >
				<img title="blood.png" alt="blood.png" src="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/thumbs/thumbs_blood.png"  />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-66" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/cells.png" title=" " class="thickbox" rel="set_5" >
				<img title="cells.png" alt="cells.png" src="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/thumbs/thumbs_cells.png"  />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-67" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/clouds.png" title=" " class="thickbox" rel="set_5" >
				<img title="clouds.png" alt="clouds.png" src="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/thumbs/thumbs_clouds.png"  />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-68" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/maze.png" title=" " class="thickbox" rel="set_5" >
				<img title="maze.png" alt="maze.png" src="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/thumbs/thumbs_maze.png"  />
			</a>
		</div>
	</div>
	 		
	<div id="ngg-image-69" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/waves.png" title=" " class="thickbox" rel="set_5" >
				<img title="waves.png" alt="waves.png" src="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/thumbs/thumbs_waves.png"  />
			</a>
		</div>
	</div>
	 	 	
	<!-- Pagination -->
 	<div class="ngg-clear"></div> 	
</div>

<h3>References</h3>
<ol>
<li><a name="1_turing"></a>Turing,A.,1952. <a target="_new" href="http://www.dna.caltech.edu/courses/cs191/paperscs191/turing.pdf">The chemical basis of morphogenesis [pdf]</a>. <i>Philosophical Transactions of the Royal Society</i>, 237 pp.37-72
</li>
<li><a name="2_grayscott"></a>Gray,P. and Scott,S.K. 1985. <a href="http://www.jstor.org/stable/2881810" target="_new">Sustained Oscillations and Other Exotic Patterns of Behavior in Isothermal Reactions.</a> <i>Journal of Physical Chemistry</i>, 89 pp.22-32
</li>
<li><a name="3_pearson"></a>Pearson,J.,1993. <a href="http://www.jstor.org/stable/2881810" target="_new">Complex patterns in a simple system.</a> <i>Science</i>, 261(5118) pp.189-192
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2009/03/reaction-diffusion-models/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>URM Emulator</title>
		<link>http://www.planetmarshall.co.uk/2009/01/urm-emulator/</link>
		<comments>http://www.planetmarshall.co.uk/2009/01/urm-emulator/#comments</comments>
		<pubDate>Sun, 25 Jan 2009 23:22:34 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Open University]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=24</guid>
		<description><![CDATA[The Unlimited Register Machine (URM), designed by Nigel Cutland, is an abstraction of a computer similar to the Turing Machine &#8211; but somewhat easier to get to grips with and more in tune with the operation of a modern computer processor.
It also happens to be the model used by the Open University&#8217;s course on Mathematical [...]]]></description>
			<content:encoded><![CDATA[<p class="pm_first"><span>T</span>he Unlimited Register Machine (URM), designed by <a href="http://www.cambridge.org/us/catalogue/catalogue.asp?isbn=9780521294652" target="_new">Nigel Cutland</a>, is an abstraction of a computer similar to the <a href="http://en.wikipedia.org/wiki/Turing_machine" target="_new">Turing Machine</a> &#8211; but somewhat easier to get to grips with and more in tune with the operation of a modern computer processor.</p>
<p>It also happens to be the model used by the Open University&#8217;s course on <a href="http://www3.open.ac.uk/courses/bin/p12.dll?C01M381" target="_new">Mathematical Logic and Number Theory</a>, and is the reason for this article since I studied the course in 2007.</p>
<p><span id="more-24"></span></p>
<h3>Emulator</h3>
<p>The implementation details of the emulator are quite interesting, using a mixture of Microsoft technologies including F# and Silverlight, however I will save that for another article for those interested in such things. To use the Emulator just hit Reset, enter the program and initial registers and click Step to trace through the program.<br />
<div class="pm_header"><a onclick="pm_toggleCodeBlock(this,'4c5169974abc7')">&#x25bc;</a> Silverlight Application</div><div id="4c5169974abc7" style="display:" class="silverlightControlHost"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="400" height="300"><param name="source" value="http://www.planetmarshall.co.uk/silverlight/Urm.App.xap"/><param name="background" value="#212121" /><!--<param name="minRuntimeVersion" value="2.0.31005.0" />--><param name="enableHtmlAccess" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;"><img src="http://storage.timheuer.com/sl4wp-ph.png" alt="Install Microsoft Silverlight" style="border-style: none; width:400px; height:300px"/></a></object><iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe></div><br /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2009/01/urm-emulator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
