<?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/category/software/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>Solving Listener Crossword 4151 with Mathematica</title>
		<link>http://www.planetmarshall.co.uk/2011/10/solving-listener-crossword-4151-with-mathematica/</link>
		<comments>http://www.planetmarshall.co.uk/2011/10/solving-listener-crossword-4151-with-mathematica/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 09:29:25 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Mathematica]]></category>

		<guid isPermaLink="false">http://www.planetmarshall.co.uk/?p=1126</guid>
		<description><![CDATA[MathsJam is a monthly meeting for people interested in recreational mathematics, and drinking of beer. At the Edinburgh meeting in August, we were presented with this Listener Crossword, from The Times Crossword Club. At the time of writing, there are &#8230; <a href="http://www.planetmarshall.co.uk/2011/10/solving-listener-crossword-4151-with-mathematica/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/crossword/puzzle.png" title="Listener Crossword 4151" class="shutterset_singlepic181" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/181__150x_puzzle.png" alt="Listener Crossword 4151" title="Listener Crossword 4151" />
</a>

<p class="pm_first"><a href="http://mathsjam.com/" target="_blank" title="MathsJam">MathsJam </a>is a monthly meeting for people interested in recreational mathematics, and drinking of beer. At the <a href="http://mathsjam.com/index.php?content=edinburgh" title="MathsJam Edinburgh" target="_blank">Edinburgh meeting</a> in August, we were presented with this <a href="http://www.listenercrossword.com/" title="The Listener Crossword" target="_blank">Listener Crossword</a>, from <a href="https://www.crosswordclub.co.uk/" title="The Times Crossword Club" target="_blank">The Times Crossword Club</a>. At the time of writing, there are plenty of solutions on the web from those who tackled the puzzle in the traditional manner of brain, pen and paper. I opted to cheat.<br />
<span id="more-1126"></span><br />
The description of the puzzle itself is quite complex, but in a nutshell the task is to substitute each of the given letters for one of the first ten prime numbers ( with no duplication ). The expression for each clue will then give a numerical solution. Substitute each digit in the solution with the first letter of its name and write the result in the crossword. There are two ways of substituting digits for letters, either in English or in German, but a solution to a given clue must be consistently one language or the other.</p>
<h2>An Algorithmic Solution</h2>
<p>I have decided to use <a href="http://www.wolfram.com/mathematica/" title="Wolfram Mathematica" target="_blank">Mathematica</a> due to its built in symbolic evaluation capabilities, but in principle any sufficiently powerful programming language would do. If you wish you can <a href="#Download">download</a> a copy of the mathematica notebook.</p>
<p>The goal of the algorithm will be to find two sets of rules that map the first 10 primes to the given letters, which give valid solutions. One straightforward way to achieve this is to enumerate every single possibility until we find two such sets. So how many possibilities are there?</p>
<p>There are <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/a466372541e515c191b8f1f549969e84.png"title="10! = 3,628,800" alt="10! = 3,628,800" style="vertical-align:top ;"/> possible sets of rules to examine. However, for each of the 27 clues, the solution generated by each rule set can be one of two options: English or German. That means that the total number of candidate solutions is<br />
<img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/44a695f6b2ea985a651430e5605b725c.png"title="&#10;10!\times 2^{27}=487,049,291,366,400&#10;" alt="&#10;10!\times 2^{27}=487,049,291,366,400&#10;" style="vertical-align:top ;"/></p>
<p>This is what&#8217;s called the &#8216;solution space&#8217;, and at a rate of 1000 candidates per second, it would take over 15,000 years to examine them all. Clearly this kind of brute force enumeration is impractical.</p>
<p>However, most of these solutions will be invalid in some way. In fact, if we trust the crossword compilers, all but two of them will be invalid. Some rules will produce solutions of the wrong size, others may conflict with other solutions in the crossword, and some may be invalid from a mathematical point of view ( such as a division that does not produce a whole number ). If instead of trying to solve the puzzle in one go, we construct &#8216;partial&#8217; solutions in some systematic fashion, we could avoid exploring parts of the solution space that cannot possibly lead to a correct solution. This is the principle behind the <a href="http://en.wikipedia.org/wiki/Backtracking" title="Wikipedia article on Backtracking" target="_blank">backtracking search</a>, one of the cornerstones of artificial intelligence. </p>
<h2>Implementation of a Backtracking Search</h2>
<p>The notion of a partial solution comes quite easily when considering a crossword puzzle, as it is simply a puzzle that is incomplete &#8211; ie, the solutions to at least one clue has been filled in. As an example, consider clue 19 Down : <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/372c8c0974114a670f97d71577e77b98.png"title="A^2" alt="A^2" style="vertical-align:top ;"/>.</p>
<p>There are ten ways of mapping the single letter in 19 down to each prime</p>
<pre class="brush: mathematica; title: ; notranslate">
In[1]  := rules = {{a -&gt; 2}, {a -&gt; 3}, {a -&gt; 5}, {a -&gt; 7}, {a -&gt; 11}, {a -&gt; 13}, {a -&gt;
   17}, {a -&gt; 19}, {a -&gt; 23}, {a -&gt; 29}}

In[2]  := a^2/.rules
Out[2] = {4, 9, 25, 49, 121, 169, 289, 361, 529, 841}
</pre>
<p>Since we know 19 Down must be three letters long, immediately we can discard the first four candidates. The remainder are all possibilities, since at this point we have no more information. Lets take the first matching possibility, <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/129e6f0f7e0fd7ed8bd23d9eee7930c6.png"title="A^2=121" alt="A^2=121" style="vertical-align:top ;"/> given by the rule <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/ce5e35c9cebf11ae5974aa56145381cb.png"title="A=11" alt="A=11" style="vertical-align:top ;"/>.</p>
<p>In English, this gives</p>
<pre class="brush: mathematica; title: ; notranslate">
In[3]  := IntegerDigits[121] /. {1 -&gt; &quot;O&quot;, 2 -&gt; &quot;T&quot;}
Out[3] = {&quot;O&quot;, &quot;T&quot;, &quot;O&quot;}
</pre>
<p>If we now look at 21 Across &#8211; <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/8cdcc93f429c0e2dbee6d8a1b257f8b1.png"title="ABI" alt="ABI" style="vertical-align:top ;"/> &#8211; There are 2 symbols to map to the remaining 9 primes ( &#8220;A&#8221; has already been mapped to 11 by 19 Down ). The number of <em>ordered</em> k-subsets of n is given by,<br />
<img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/6d7a125c468b365be35d6b8195f692f0.png"title="&#10;_nP^k = \frac{n!}{(n-k)!}&#10;" alt="&#10;_nP^k = \frac{n!}{(n-k)!}&#10;" style="vertical-align:top ;"/></p>
<p>So we have <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/0949100eaa2bca627621bb76f08199cd.png"title="9!/7!=90" alt="9!/7!=90" style="vertical-align:top ;"/> new sets of rules to examine</p>
<pre class="brush: mathematica; title: ; notranslate">
In[4] := rules = {a -&gt; 11, b -&gt; #[[1]], i -&gt; #[[2]]} &amp; /@
 Permutations[{2, 3, 5, 7, 13, 17, 19, 23, 29}, {2}]
Out[4] = {{a -&gt; 11, b -&gt; 2, i -&gt; 3}, {a -&gt; 11, b -&gt; 2, i -&gt; 5},...

In[5] := a b i/. rules
Out[5] = {66, 110, 154, 286, 374, 418, 506, 638, 66,...
</pre>
<p>Again, many of the partial solutions produced by these rules are invalid. Only 36 are the required 4 digits long, and we also now have information about the form of this solution. We know that the first letter is &#8220;T&#8221;, given to us by the puzzle setter, and also that the last letter is &#8220;T&#8221;, because of our solution to 19 Down : &#8220;OTO&#8221;.</p>
<pre class="brush: mathematica; title: ; notranslate">
In[6] := candidates = Select[a b i /. rules, Length[IntegerDigits[#]] == 4 &amp;]
Out[6] = {1045, 1265, 1595, 1001, 1309, 1463, 1771, 2233,...

In[7] := englishRules = {0 -&gt; &quot;Z&quot;, 1 -&gt; &quot;O&quot;, 2 -&gt; &quot;T&quot;, 3 -&gt; &quot;T&quot;,...
In[8] := germanRules = {0 -&gt; &quot;N&quot;, 1 -&gt; &quot;E&quot;, 2 -&gt; &quot;Z&quot;, 3 -&gt; &quot;D&quot;,...
In[9] := candidates = StringJoin @@@ ((IntegerDigits /@ candidates)
   /. Join[english, german])
Out[9] = {&quot;OZFF&quot;, &quot;OTSF&quot;, &quot;OFNF&quot;, &quot;OZZO&quot;, &quot;OTZN&quot;, &quot;OFST&quot;,...

In[10] := Select[candidates, StringMatchQ[#, RegularExpression[&quot;T..T&quot;]] &amp;]
Out[10] = {&quot;TTTT&quot;, &quot;TFFT&quot;, &quot;TTTT&quot;, &quot;TFFT&quot;}
</pre>
<p>Note the duplicates. This is because <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/234da07d44fe9b1f1a2d23844f177e16.png"title="B I = I B " alt="B I = I B " style="vertical-align:top ;"/>, but we cannot eliminate them because the rules used to produce them are different, and so will lead to different partial solutions. By applying the constraints systematically, we have reduced the number of potential solutions for 21 Across from 90 to just 4.</p>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/crossword/alg.png" title="A portion of the backtracking search algorithm." class="shutterset_singlepic178" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/178__256x_alg.png" alt="Algorithm" title="Algorithm" />
</a>
We then repeat this process in a recursive manner, using one of the valid solutions to 21 across, and the rules that  were used to generate it, to examine the next clue. We continue in this fashion until either the crossword is filled, or we reach a dead end ( which is more likely ). If we reach a dead end, we backtrack ( hence the name ) to one of the possibilities we haven&#8217;t tried yet. </p>
<p>Why is this approach any more efficient than the brute force enumeration described above? The key is the generation of partial solutions in a tree like fashion, and the ability to eliminate them when we know that they could not possibly form part of a full solution. When we eliminate such a partial solution because it didn&#8217;t satisfy the constraints, we eliminate all the possible solutions leading from that branch. For example, when we eliminated the rule <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/1e1a0e85efabbd0e97200a1aada32fa1.png"title="A=2" alt="A=2" style="vertical-align:top ;"/> because it produced a solution to 19 Down that was too short, it eliminates not just one solution but all <img src="http://www.planetmarshall.co.uk/wp-content/plugins/latex/latexrender/pictures/a28fcb488e01635362c81adeeb069a7f.png"title=" 9!\times 2^{27}=48,704,929,136,640 " alt=" 9!\times 2^{27}=48,704,929,136,640 " style="vertical-align:top ;"/> solutions incorporating that rule. Not bad for a single calculation.</p>
<h2>The Solution</h2>
<p>In abbreviated form, the algorithm looks something like this.</p>
<pre class="brush: mathematica; title: ; notranslate">
ExamineNextCandidate[{solved_, unsolved_},
  rules_] := {solved, rules} /; Length[unsolved] == 0

ExamineNextCandidate[{solved_, unsolved_}, rules_] := Module[{...},
   {clueIdx, cluePattern} = First[unsolved];
  nextRuleSet =
   GenerateRules[GetSymbolsInClue[ClueExpression[clueIdx]], rules];
  solution = Null;
  While[Length[nextRuleSet] &gt; 0 &amp;&amp; solution == Null,
   nextRule = First[nextRuleSet];
   nextRuleSet = Rest[nextRuleSet];
   candidates =
    StringJoin @@@ (IntegerDigits[
        ClueExpression[clueIdx] /. nextRule] /. {english, german});
   candidates = FilterCandidatesByConstraints[candidates];
   If[Length[candidates] &gt; 0,
     nextPatterns =
      GenerateNewPatterns[unsolved, {#, clueIdx}] &amp; /@ candidates;
     nextArgs = {Append[solved, First[#]], Rest[#]} &amp; /@ nextPatterns;
     While[solution == Null &amp;&amp; Length[nextArgs] &gt; 0,
      solution = ExamineNextCandidate[First[nextArgs], nextRule];
      nextArgs = Rest[nextArgs]
      ];
     ]
    ];
  solution
</pre>
<p>Note that the function <code>ExamineNextCandidate</code> calls itself until the pattern on the list of unsolved solutions is met, ie the list is empty. We call this function using an initially empty rules list, and the patterns provided by the puzzle setter.</p>
<pre class="brush: mathematica; title: ; notranslate">
In[1]:=ExamineNextCandidate[{{}, {...,{20, &quot;..&quot;}, {21, &quot;T...&quot;}, {23, &quot;....&quot;},...}, {}]
Out[1]={...,{20, &quot;FE&quot;}, {21, &quot;TTTT&quot;}, {23, &quot;FZFO&quot;},...}
</pre>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/crossword/clue1.png" title="The solution for the first grid" class="shutterset_singlepic179" >
	<img class="ngg-singlepic ngg-left" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/179__256x_clue1.png" alt="Solution 1" title="Solution 1" />
</a>
 On my dual core netbook ( A 2010 Alienware M11xR2 ), this took just over 2 seconds to find a solution.</p>
<p>For the second puzzle, we alter the pattern to specify that the first letter of 21 Across ( and last of 9 Down ) can be any letter <em>except</em> &#8216;T&#8217;, using the regular expression <code>"[^T]..."</code>. In the code snippets, I have abbreviated the output somewhat. See the attached Mathematica notebook file for full details.</p>
<pre class="brush: mathematica; title: ; notranslate">
In[2]:=ExamineNextCandidate[{{}, {...,{20, &quot;..&quot;}, {21, &quot;[^T]...&quot;}, {23, &quot;....&quot;},...}, {}]
Out[2]={...,{20, &quot;EE&quot;}, {21, &quot;FFTT&quot;}, {23, &quot;FZFO&quot;},...}
</pre>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/crossword/clue2.png" title="The solution for the second grid" class="shutterset_singlepic180" >
	<img class="ngg-singlepic ngg-right" src="http://www.planetmarshall.co.uk/wp-content/gallery/cache/180__256x_clue2.png" alt="Solution 2" title="Solution 2" />
</a>
 Finally, the last part of the puzzle is to complete the following task:</p>
<blockquote><p>&#8220;Solvers must identify the English transcriptions of the answers entered using German in one of the grids, which, in clue order, form two words of equal length that are to be entered below the grids, one on each side of the colon; this will relate to a claim made above.&#8221;
</p></blockquote>
<p>To identify the answers entered in German, we apply the rules returned by the solver to the original expressions and use the German digit replacement rules. We then compare these to the completed grid.</p>
<pre class="brush: mathematica; title: ; notranslate">
In[1]:={solution,rules}=ExamineNextCandidate[{{}, {...,{20, &quot;..&quot;}, {21, &quot;T...&quot;}, {23, &quot;....&quot;},...}, {}]
Out[1]={...,{a -&gt; 11, b -&gt; 17, d -&gt; 19, e -&gt; 7,...}}

In[2]:=Intersection[(clues /. rules1) /. {a_, b_} :&gt; {a,
    IntegerDigits[b] /. german}, solution][[;;,1]]
Out[2]={10, 11, 13, 16, 25, 29, 30}

In[3]:=(Select[clues, MemberQ[%2, First[#]] &amp;] /. rules) /. {a_, b_} :&gt; {a,
    StringJoin @@ (IntegerDigits[b] /. english)}
Out[3]={{10, &quot;SF&quot;}, {11, &quot;NF&quot;}, {13, &quot;FOO&quot;}, {16, &quot;TNOTE&quot;}, {25, &quot;NON&quot;}, {29,
   &quot;SENSE&quot;}, {30, &quot;SSF&quot;}}
</pre>
<p>Having identified those clues, we reevaluate the expressions this time using the English rules. There are 4 clues that are the same in both German and English, but it is pretty clear that the required words are &#8220;<strong>Footnote</strong>&#8221; and &#8220;<strong>Nonsense</strong>&#8221;</p>
<h2>Download</h2>
<p><a name="Download"/><a href="http://www.planetmarshall.co.uk/code/xword/xword.nb" title="Mathematica Notebook" target="_blank">Mathematica Notebook (111K)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.planetmarshall.co.uk/2011/10/solving-listener-crossword-4151-with-mathematica/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>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 &#8230; <a href="http://www.planetmarshall.co.uk/2010/04/visualizing-the-prime-ministerial-debates/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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="shutterset_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><br />
<h3>Preparing the data</h3>
<p>
<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="shutterset_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 &quot;Save as Text&quot; 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>
<pre class="brush: bash; title: ; notranslate">
awk 'BEGIN {RS=&quot;&quot;; FS=&quot;[@]&quot;} $1==&quot;NC&quot; { print $2 }' debate.txt &gt; clegg.txt
</pre>
<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="shutterset_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>&#8216;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>
<pre class="brush: python; title: ; notranslate">
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>
<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>
<pre class="brush: py; gutter: false; toolbar: false;"># this operation takes some time to execute
taggedwords=nltk.pos_tag(words)
nouns=[word for (word,tag) in words if t == 'NN']</pre>
<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>
<pre class="brush: python; title: ; notranslate">
nounfrequencies = nltk.FreqDist(nouns)
</pre>
<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 />
  <br /><a name="gallery"></a></p>
<h3>Gallery of word clouds from the first debate</h3>

<div class="ngg-galleryoverview" id="ngg-gallery-13-805">

	<!-- Slideshow link -->
	<div class="slideshowlink">
		<a class="slideshowlink" href="http://www.planetmarshall.co.uk/2010/04/visualizing-the-prime-ministerial-debates/?show=slide">
			[Show as slideshow]		</a>
	</div>

	
	<!-- 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="shutterset_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="100" height="64" />
							</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="shutterset_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="100" height="64" />
							</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="shutterset_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="100" height="64" />
							</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="shutterset_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="100" height="64" />
							</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="shutterset_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="100" height="65" />
							</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="shutterset_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="100" height="65" />
							</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="shutterset_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="100" height="63" />
							</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="shutterset_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="100" height="65" />
							</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="shutterset_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="100" height="65" />
							</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 &#8230; <a href="http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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="shutterset_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="shutterset_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>
<p>
<a href="http://www.planetmarshall.co.uk/wp-content/gallery/infrared/irgreyscale.jpg" title="A greyscale representation of a Near Infra Red image" class="shutterset_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="shutterset_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="shutterset_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>

<div class="ngg-galleryoverview" id="ngg-gallery-12-705">

	<!-- Slideshow link -->
	<div class="slideshowlink">
		<a class="slideshowlink" href="http://www.planetmarshall.co.uk/2010/03/near-infra-red-pseudocolour-using-lab-colour-separations/?show=slide">
			[Show as slideshow]		</a>
	</div>

	
	<!-- 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="shutterset_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="100" height="74" />
							</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="shutterset_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="92" height="75" />
							</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="shutterset_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="92" height="75" />
							</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="shutterset_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="80" height="75" />
							</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="shutterset_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="100" height="74" />
							</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="shutterset_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="100" height="74" />
							</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 &#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>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 &#8230; <a href="http://www.planetmarshall.co.uk/2009/11/searching-msdn-using-google/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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 &#8230; <a href="http://www.planetmarshall.co.uk/2009/07/using-merged-resourcedictionaries-in-silverlight-themes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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>
<pre lang="xml">
<ResourceDictionary>
 <ResourceDictionary.MergedDictionaries>
  <ResourceDictionary Source="/MergedTheme;component/Styles/Button.xaml"/>
 <ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</pre>
<pre lang="csharp">
public class MergedTheme : Theme {
 public MergedTheme() :
  base(typeof(MergedTheme).Assembly, "MergedTheme.Theme.xaml") {
  DefaultStyleKey = typeof(MergedTheme);
 }
}
</pre>
<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>
<pre lang="csharp">
///
<summary>
/// Test that styles contained in a  merged dictionary can be successfully applied
/// </summary>

[TestMethod]
[Asynchronous]
[Description("Test that a dictionary contining merged dictionaries can be successfully loaded.")]
public void TestResourceDictionaryWithMergedDictionaries() {
 Uri uri = new Uri("System.Windows.Controls.Testing.Theming;
  component/ImplicitStyleManager/MergedResourceDictionary.xaml", UriKind.Relative);
 TestAuto( (stackPanel) => {
  SetResourceDictionaryUri(stackPanel, uri);
  ImplicitStyleManager.SetApplyMode(stackPanel, ImplicitStylesApplyMode.Auto);
  }, Colors.Blue);
}
</pre>
<p>The test fails as we would expect.</p>

<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="shutterset_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>

<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>
<pre lang="xml">
<ContentControl>
 <ContentControl.Resources>
  <ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="[...]/ResourceDictionaryForMerge.xaml" />
  </ResourceDictionary.MergedDictionaries>
 </ContentControl.Resources>
</ContentControl>
</pre>
<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>
<pre lang="csharp">
private static void ParseElement(XmlReader reader, XmlWriter writer, bool checkTypes) {
 if (reader.Depth == 0) {...}
 else {
  // handle merged dictionaries by wrapping them in a ResourceDictionary element
  if (reader.Name == "ResourceDictionary.MergedDictionaries") {
   XElement parent = new XElement("ResourceDictionary");
   parent.Add(XElement.ReadFrom(reader));
   writer.WriteRaw(parent.ToString());
  }
  else { ... }
 }
}
</pre>
<p>Having made the change, we rerun the test.</p>

<a href="http://www.planetmarshall.co.uk/wp-content/gallery/sltoolkit/testpass.png" title="How I love the green bar" class="shutterset_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>

<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>

<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="shutterset_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>

<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 &#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>
		<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 &#8230; <a href="http://www.planetmarshall.co.uk/2009/01/urm-emulator/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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 />
[silverlight: Urm.App.xap,400,300,false] </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>

