<?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; C#</title>
	<atom:link href="http://www.planetmarshall.co.uk/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.planetmarshall.co.uk</link>
	<description>Andrew Marshall&#039;s blog</description>
	<lastBuildDate>Thu, 10 Nov 2011 17:33:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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 &#8230; <a href="http://www.planetmarshall.co.uk/2010/06/drawing-geodesic-curves-using-the-bing-maps-silverlight-control/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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="shutterset_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 />
[silverlight: Geodesic.xap,520,384,false]</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>$$!begin{pmatrix} x \ y end{pmatrix} = begin{pmatrix} r cos t \ r sin t end{pmatrix} $$</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>$$!begin{pmatrix} x \ y \ z end{pmatrix} = mathbf{R}cdotbegin{pmatrix} r cos t \ r sin t end{pmatrix} $$</p>
<p>where $$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 />
$$!mathbf{C}(t) =begin{pmatrix} lambda \ tanh^{-1} left(sin phi right)end{pmatrix} = begin{pmatrix} tan^{-1}left(y/xright)\ tanh^{-1}z end{pmatrix}$$<br />
Where $$lambda$$ and $$phi$$ are the longitude and latitude of the point to be projected, respectively. Writing the equation out in full gives,</p>
<p>$$!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 />
$$</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="shutterset_singlepic141" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/index.php?callback=image&amp;pid=141&amp;width=150&amp;height=&amp;mode=" 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 />
$$!t = -tan^{-1}frac{R_{1,2}}{R_{2,2}} $$<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>3</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 &#8230; <a href="http://www.planetmarshall.co.uk/2010/01/silverlight-and-cuda-interop/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/cuda-interop/mandrill.jpg" title="" class="shutterset_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 />
[silverlight: cuda_interop/SlCudaInteropDemo.xap,520,580,false]</p>
<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>
<pre title="Calling COM from Silverlight" lang="csharp">
// note that ComAutomationFactory has become AutomationFactory
// in Silverlight 4 RC
dynamic cuda = AutomationFactory.CreateObject("CudaServer.Application");
float[] data = new [] {1.0f, 3.14f };
dynamic retData = cuda.Process( data );
// retData is a managed float array</pre>
<pre title="Returning data to Silverlight from MFC via COM" lang="cpp">VARIANT CCudaServer::Process(VARIANT &amp;data)
{
  SAFEARRAY *pSrcData =  data.parray;

  // this will copy the safe array into the variant
  CComVariant var(pSrcData);

  // when we return the VARIANT containing the SAFEARRAY
  // it will be marshaled to Silverlight as a managed array
  VARIANT retVal;
  VariantInit( &amp;retVal );
  var.Detach( &amp;retVal );
  retVal.vt = VT_ARRAY | VT_R4;
  return retVal;
}</pre>
<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>

<a href="http://www.planetmarshall.co.uk/wp-content/gallery/cuda-interop/slcuda_component.png" title="Component diagram for demo application" class="shutterset_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>

<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>
<pre title="Updating bitmap using property accessors" lang="csharp">for (int j = 0; j &lt; bmp.PixelHeight; ++j)
{
  for (int i = 0; i &lt; bmp.PixelWidth; ++i)
  {
     // update pixels
   }
}</pre>
<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>
<pre title="Updating bitmap with cached variables" lang="csharp">int pxWidth =  bmp.PixelWidth;
int pxHeight = bmp.PixelHeight;
for (int j = 0; j &lt; pxHeight; ++j)
{
  for (int i = 0; i &lt; pxWidth; ++i)
  {
     // update pixels
   }
}</pre>
<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>
<pre title="Row major access pattern" lang="cuda">__global__ void kernel( float *destData, float *srcData, int stride, int height )
{
  // suboptimal access. Each thread accesses elements
 // in a striding pattern
  int rowStart = (blockDim.x*blockIdx.x+threadIdx.x)*stride;
  for ( int i = rowStart; i < rowStart+stride; ++i ) {
    destData[i] = srcData[i];
  }
}</pre>
<pre title="Column major access patern" lang="cuda">__global__ void kernel( float *destData, float *srcData, int stride, int height )
{
  // optimal access pattern, each thread accesses adjacent elements
  int colStart = blockDim.x*blockIdx.x+threadIdx.x;
  // this case, 16*sizeof(float)= 64 bytes
  for ( int i = colStart ; i < colStart+(stride*height); i+=stride ) {
    destData[i] = srcData[i];
  }
}</pre>
<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>8</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 &#8230; <a href="http://www.planetmarshall.co.uk/2009/04/implentation-of-the-reaction-diffusion-simulation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/blood.png" title="" class="shutterset_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="shutterset_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>
<pre title="Rectangular array implementation" lang="csharp">for (int j = 0; j &lt; H; j++)
{
 int jm = j != 0 ? j - 1 : H - 1;
 int jp = j != H - 1 ? j + 1 : 0;
 for (int i = 0; i &lt; W; i++)
 {
  int im = i != 0 ? i - 1 : W - 1;
  int ip = i != W - 1 ? i + 1 : 0;
  double d2u = U[j,im]+U[j,ip]+U[jm,i]+U[jp,i]-4*U[j,i];
  double d2v = V[j,im]+V[j,ip]+V[jm,i]+V[jp,i]-4*V[j,i];
  double uv2 = U[j,i]*V[j,i]*V[j,i];
  Uu[j,i] = du*d2u-uv2+F+U[j,i]*one_minus_F;
  Vv[j,i] = dv*d2v+uv2+V[j,i]*one_minus_F_minus_k;
 }
}</pre>
<p>On my machine this took on the order of 600ms to perform 100 iterations. Using jagged arrays instead, we have the following</p>
<pre title="Jagged array implementation" lang="csharp">for (int j = 0; j &lt; H; j++)
{
 int jm = j != 0 ? j - 1 : H - 1;
 int jp = j != H - 1 ? j + 1 : 0;
 for (int i = 0; i &lt; W; i++)
 {
  int im = i != 0 ? i - 1 : W - 1;
  int ip = i != W - 1 ? i + 1 : 0;
  double d2u = U[j][im]+U[j][ip]+U[jm][i]+U[jp][i]-4*U[j][i];
  double d2v = V[j][im]+V[j][ip]+V[jm][i]+V[jp][i]-4*V[j][i];
  double uv2 = U[j][i]*V[j][i]*V[j][i];
  Uu[j][i] = du*d2u-uv2+ F+U[j][i]*one_minus_F;
  Vv[j][i] = dv*d2v+uv2+V[j][i]*one_minus_F_minus_k;
 }
}</pre>
<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>
<pre title="Jagged array with outer loop caching" lang="csharp">for (int j = 0; j &lt; H; j++)
{
 int jm = j != 0 ? j - 1 : H - 1;
 int jp = j != H - 1 ? j + 1 : 0;
 var u_m = U[jm];
 var u = U[j];
 var u_p = U[jp];
 var v_m = V[jm];
 var v = V[j];
 var v_p = V[jp];
 var uu = Uu[j];
 var vv = Vv[j];
 for (int i = 0; i &lt; W; i++)
 {
  int im = i != 0 ? i - 1 : W - 1;
  int ip = i != W - 1 ? i + 1 : 0;
  double d2u = u[im]+u[ip]+u_m[i]+u_p[i]-4*u[i];
  double d2v = v[im]+v[ip]+v_m[i]+v_p[i]-4*v[i];
  double uv2 = u[i]*v[i] *v[i];
  uu[i] = du*d2u-uv2+F+u[i]*one_minus_F;
  vv[i] = dv*d2v+uv2+v[i]*one_minus_F_minus_k;
 }
}</pre>
<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&#8216;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 &#8230; <a href="http://www.planetmarshall.co.uk/2009/03/reaction-diffusion-models/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/reaction_diffusion/maze.png" title="" class="shutterset_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>&#8216;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 />
<img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/a7d70e02c93cb96e6b0012ecebb75b57.png"title="&#10;\frac{\partial}{\partial t}\mathbf{q}=\mathbf{D}\nabla^2\mathbf{q}+\mathbf{R}(\mathbf{q})&#10;" alt="&#10;\frac{\partial}{\partial t}\mathbf{q}=\mathbf{D}\nabla^2\mathbf{q}+\mathbf{R}(\mathbf{q})&#10;" style="vertical-align:top ;"/></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 />
<img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/0066159d03a0b2aa45c47b46c63ac571.png"title="&#10;\begin{align*}&#10;\frac{\partial}{\partial t}U&amp;#038;=D_u\nabla^2U-UV^2+F(1-U) \\&#10;\frac{\partial}{\partial t}V&amp;#038;=D_v\nabla^2V+UV^2-(F+k)V&#10;\end{align*}&#10;" alt="&#10;\begin{align*}&#10;\frac{\partial}{\partial t}U&amp;#038;=D_u\nabla^2U-UV^2+F(1-U) \\&#10;\frac{\partial}{\partial t}V&amp;#038;=D_v\nabla^2V+UV^2-(F+k)V&#10;\end{align*}&#10;" style="vertical-align:top ;"/></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>[silverlight: ReactionDiffusion.xap, 450, 300]</p>
<h3>Gallery</h3>
<div class="ngg-galleryoverview" id="ngg-gallery-5-124">

	<!-- Slideshow link -->
	<div class="slideshowlink">
		<a class="slideshowlink" href="http://www.planetmarshall.co.uk/2009/03/reaction-diffusion-models/?show=slide">
			[Show as slideshow]		</a>
	</div>

	
	<!-- 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="shutterset_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="shutterset_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="shutterset_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="shutterset_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="shutterset_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>
	</channel>
</rss>

