<?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>Index Out Of Range</title>
	<atom:link href="http://www.frenk.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.frenk.com</link>
	<description>Francesco De Vittori</description>
	<lastBuildDate>Mon, 07 May 2012 10:23:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Simple color-based search by image in F#</title>
		<link>http://www.frenk.com/2012/05/simple-color-based-search-by-image-in-f/</link>
		<comments>http://www.frenk.com/2012/05/simple-color-based-search-by-image-in-f/#comments</comments>
		<pubDate>Sun, 06 May 2012 15:15:46 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Computer]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Image processing]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=424</guid>
		<description><![CDATA[Last week I was playing with a photomosaic composer toy project and needed a simple search by image engine. By search by image I mean searching a database for an image similar to a given one. In this tutorial I will show you how you can implement this functionality –with some obvious limitations– in an [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I was playing with a photomosaic composer toy project and needed a simple <em>search by image</em> engine. By <em>search by image</em> I mean searching a database for an image similar to a given one. In this tutorial I will show you how you can implement this functionality –with some obvious limitations– in an extremely simple way just by looking at an image’s color distribution.</p>
<p>If you are looking for feature similarity (shapes, patterns, etc.) you most likely need edge detection algorithms (<a href="http://en.wikipedia.org/wiki/Gabor_filter">linear filters</a> or <a href="http://people.csail.mit.edu/torralba/code/spatialenvelope/">other similar methods</a>), which give excellent results but are usually quite complicated. I suppose that’s the way most image search engines work. Alternatively <a href="http://www.cs.cmu.edu/~har/visapp2006.pdf">this paper</a> describes the sophisticated color-based approach used by Google’s skin-detection engine.</p>
<p>In many cases however, finding images with a perceptually similar color distribution can be enough.<br />If you are in this situation, you may get away with a very simple technique that still gives pretty good results with a minimal implementation effort. The technique is long known and widely used, but if you have no experience in image processing this step-by-step guide may be a fun and painless warm-up to the topic.</p>
<p>I’ll show the concept with the help of F# code, but the approach is so straightforward that you should understand it even without prior knowledge of the language.</p>
<h2>TL;DR:</h2>
<p>This is the high level outline of the process.</p>
<p>Just once, to build a database “index”:</p>
<ul>
<li>Create a normalized 8-bit color distribution histogram of each image in the database. </li>
</ul>
<p>For every query:</p>
<ul>
<li>Create a normalized 8-bit color distribution histogram of the query image.
<li>Search the database for the histogram closest to the query using some probability distribution distance function. </li>
</ul>
<p>If you are still interested in the details of each step, please read on.</p>
<h2>Extracting an image’s <em>color signature</em></h2>
<p>Given that we want to compare images, we’ll have to transform them into something that can be easily compared. We could just compute the average color of all pixels in an image, but this is not very useful in practice. Instead, we will use a <strong>color histogram</strong>, i.e. we will count the number of pixels of each possible color.</p>
<p>A color histogram is created in four steps:</p>
<ol>
<li>Load/decode the image into an array of pixels.
<li>Downsample the pixels to 8-bit “truecolor” in order to reduce the color space to 256 distinct colors.
<li>Count the number of pixels for each given color.
<li>Normalize the histogram (to allow the comparison of images with different size).</li>
</ol>
<h3>1. Loading the image<br /></h3>
<p>This is almost trivial in most languages/framework. Here’s the F# code using the System.Windows.Media APIs:</p>
<div id="gist-2585956" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">open</span> <span class="nn">System</span><span class="p">.</span><span class="nn">Windows</span><span class="p">.</span><span class="nc">Media</span></div><div class='line' id='LC2'><span class="k">open</span> <span class="nn">System</span><span class="p">.</span><span class="nn">Windows</span><span class="p">.</span><span class="nn">Media</span><span class="p">.</span><span class="nc">Imaging</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="c1">/// Returns the pixels of an image as a byte array,</span></div><div class='line' id='LC5'><span class="c1">/// in form [Alpha, B, G, R, Alpha, B, G, R, ...]</span></div><div class='line' id='LC6'><span class="k">let</span> <span class="n">getPixels</span> <span class="n">imgPath</span> <span class="o">=</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BitmapImage</span> <span class="o">(</span><span class="k">new</span> <span class="nn">System</span><span class="p">.</span><span class="nc">Uri</span> <span class="o">(</span><span class="n">imgPath</span><span class="o">))</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">source</span> <span class="o">=</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="n">s</span><span class="o">.</span><span class="nc">Format</span> <span class="o">&lt;&gt;</span> <span class="nn">PixelFormats</span><span class="p">.</span><span class="nc">Bgr32</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">then</span> <span class="k">new</span> <span class="nc">FormatConvertedBitmap</span> <span class="o">(</span><span class="n">s</span><span class="o">,</span> <span class="nn">PixelFormats</span><span class="p">.</span><span class="nc">Bgr32</span><span class="o">,</span> <span class="k">null</span><span class="o">,</span> <span class="mi">0</span><span class="o">.)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">:&gt;</span> <span class="nc">BitmapSource</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">else</span> <span class="n">s</span> <span class="o">:&gt;</span> <span class="nc">BitmapSource</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">width</span> <span class="o">=</span> <span class="n">source</span><span class="o">.</span><span class="nc">PixelWidth</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">height</span> <span class="o">=</span> <span class="n">source</span><span class="o">.</span><span class="nc">PixelHeight</span>    </div><div class='line' id='LC16'><br/></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">pixels</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">create</span> <span class="o">(</span><span class="n">width</span> <span class="o">*</span> <span class="n">height</span> <span class="o">*</span> <span class="mi">4</span><span class="o">)</span> <span class="mi">0</span><span class="n">uy</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">source</span><span class="o">.</span><span class="nc">CopyPixels</span> <span class="o">(</span><span class="n">pixels</span><span class="o">,</span> <span class="n">width</span> <span class="o">*</span> <span class="mi">4</span><span class="o">,</span> <span class="mi">0</span><span class="o">)</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">pixels</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2585956/90d4db9cd0a6ec90413decc04693dc05a9d62ff8/readPixels.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2585956#file_read_pixels.fs" style="float:right;margin-right:10px;color:#666">readPixels.fs</a>
            <a href="https://gist.github.com/2585956">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>&nbsp;</p>
<h3>2. Downsampling 32-bit color to 8-bit</h3>
<p>&nbsp;</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="8bit" border="0" alt="8bit" src="http://www.frenk.com/wp-content/uploads/2012/05/8bit2.png" width="388" height="163"></p>
<p>With the help of some basic bitwise operations we reduce pixels from 32 bits down to 8. We discard the alpha channel and keep 2 bits for blue (out of the original 8), 3 for red and 3 for green (we discard the least significant bits of each color component). The result is that each pixel (being a byte) can represent one of exactly 256 colors. We obviously loose some color detail because we cannot represent all the original gradients, but having a smaller color space keeps the histogram size manageable.</p>
<div id="gist-2586024" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">/// Combines the given R, G, B values (8 bits each)</span></div><div class='line' id='LC2'><span class="c1">/// into a single byte.</span></div><div class='line' id='LC3'><span class="k">let</span> <span class="n">to8bpp</span> <span class="n">red</span> <span class="n">green</span> <span class="n">blue</span> <span class="o">=</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">b</span> <span class="o">=</span> <span class="n">blue</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">6</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">g</span> <span class="o">=</span> <span class="n">green</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">5</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">r</span> <span class="o">=</span> <span class="n">red</span> <span class="o">&gt;&gt;&gt;</span> <span class="mi">5</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="mi">0</span><span class="n">uy</span> <span class="o">|||</span> <span class="o">(</span><span class="n">r</span> <span class="o">&lt;&lt;&lt;</span> <span class="mi">5</span><span class="o">)</span> <span class="o">|||</span> <span class="o">(</span><span class="n">g</span> <span class="o">&lt;&lt;&lt;</span> <span class="mi">2</span><span class="o">)</span> <span class="o">|||</span> <span class="n">b</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="c1">/// Converts 32-bits ABGR to 8-bits &quot;truecolor&quot;: 2 bits for blue,</span></div><div class='line' id='LC10'><span class="c1">/// 3 for green, 3 for red (RGB).</span></div><div class='line' id='LC11'><span class="c1">/// Expects an array in form [ Alpha, B, G, R, Alpha, B, G, R, ... ]</span></div><div class='line' id='LC12'><span class="c1">/// Returns an array of pixels where each pixel is a byte (RGB).</span></div><div class='line' id='LC13'><span class="k">let</span> <span class="n">to8bit</span> <span class="n">px32bpp</span> <span class="o">=</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">[|</span> <span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="mi">0</span><span class="o">..</span><span class="mi">4</span><span class="o">..((</span><span class="nn">Array</span><span class="p">.</span><span class="n">length</span> <span class="n">px32bpp</span><span class="o">)</span> <span class="o">-</span> <span class="mi">4</span><span class="o">)</span> <span class="o">-&gt;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">to8bpp</span> <span class="n">px32bpp</span><span class="o">.[</span><span class="n">i</span> <span class="o">+</span> <span class="mi">2</span><span class="o">]</span> <span class="n">px32bpp</span><span class="o">.[</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="o">]</span> <span class="n">px32bpp</span><span class="o">.[</span><span class="n">i</span><span class="o">]</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|]</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2586024/bd293eee17b6029ed14d939d431dbc7d79cc27a7/8bit.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2586024#file_8bit.fs" style="float:right;margin-right:10px;color:#666">8bit.fs</a>
            <a href="https://gist.github.com/2586024">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><em>Note:</em> in general 8-bit images use a palette, i.e. every pixel value is a pointer to a color in a 256-color palette. That way the palette can be optimized to only include the most frequent color in the image. In our case the benefit would not be worth the trouble as we would need a common palette across all the images anyways (plus the above method is faster and simpler).</p>
<h3>3. Creating the histogram</h3>
<p>&nbsp;</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="histogram" border="0" alt="histogram" src="http://www.frenk.com/wp-content/uploads/2012/05/histogram.png" width="375" height="169"></p>
<p>Nothing special here: we just count the number of pixels that are of a given color. The histogram is nothing more than a 256-elements array of integers (plus the image file name). You can read it like “this image has 23 “light green” pixels, 10 “dark red” pixels, etc.”<br />We then normalize the histogram by dividing each value by the total number of pixels so that each color amount is a float value in the 0 .. 1 range, where for ex. 0.3 means that a picture has 30% of pixels of that given color.</p>
<div id="gist-2586142" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">type</span> <span class="nc">Histogram</span> <span class="o">=</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nc">Data</span> <span class="o">:</span> <span class="kt">float</span> <span class="kt">array</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nc">FileName</span> <span class="o">:</span> <span class="kt">string</span></div><div class='line' id='LC4'><span class="o">}</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="k">let</span> <span class="n">makeHistogram</span> <span class="o">(</span><span class="n">fileName</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">=</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// gets the image pixels</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">pixels</span> <span class="o">=</span> <span class="n">getPixels</span> <span class="n">fileName</span> <span class="o">|&gt;</span> <span class="n">to8bit</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// creates an empty histogram</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">histogram</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">create</span> <span class="mi">256</span> <span class="mi">0</span><span class="o">.</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">pixelCount</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">length</span> <span class="n">pixels</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// counts the number of occurrences of every color</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="mi">0</span><span class="o">..</span><span class="n">pixelCount</span> <span class="o">-</span> <span class="mi">1</span> <span class="k">do</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">color</span> <span class="o">=</span> <span class="kt">int</span> <span class="n">pixels</span><span class="o">.[</span><span class="n">i</span><span class="o">]</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">histogram</span><span class="o">.[</span><span class="n">color</span><span class="o">]</span> <span class="o">&lt;-</span> <span class="n">histogram</span><span class="o">.[</span><span class="n">color</span><span class="o">]</span> <span class="o">+</span> <span class="mi">1</span><span class="o">.</span></div><div class='line' id='LC18'><br/></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// normalizes the histogram</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">normalized</span> <span class="o">=</span> <span class="o">[|</span> <span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="mi">0</span><span class="o">..</span><span class="n">histogram</span><span class="o">.</span><span class="nc">Length</span> <span class="o">-</span> <span class="mi">1</span> <span class="o">-&gt;</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">System</span><span class="p">.</span><span class="nn">Math</span><span class="p">.</span><span class="nc">Round</span><span class="o">(</span><span class="n">histogram</span><span class="o">.[</span><span class="n">i</span><span class="o">]</span> <span class="o">/</span> <span class="kt">float</span> <span class="n">pixelCount</span><span class="o">,</span> <span class="mi">4</span><span class="o">)</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|]</span></div><div class='line' id='LC23'><br/></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// returns the image &quot;signature&quot;</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span> <span class="nn">Histogram</span><span class="p">.</span><span class="nc">Data</span> <span class="o">=</span> <span class="n">normalized</span><span class="o">,</span> <span class="nc">FileName</span> <span class="o">=</span> <span class="n">fileName</span> <span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2586142/ab1003973bdfb627e9093a1cc4a2693c47e3171c/histogram.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2586142#file_histogram.fs" style="float:right;margin-right:10px;color:#666">histogram.fs</a>
            <a href="https://gist.github.com/2586142">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>&nbsp;</p>
<h2>Comparing color histograms</h2>
<p>Now we have a collection of histograms (the database) and a query histogram. In order to find the best matching image, we need a way to measure how similar two histograms are. In other words we need a <em>distance</em> function that quantifies the similarity between two histograms (and thus between two images).</p>
<p>You probably have noticed that a normalized histogram is in fact a discrete probability distribution. Every value is between 0 and 1 and the sum of all values is 1. This means we can use statistical “<a href="http://en.wikipedia.org/wiki/Goodness_of_fit">goodness of fit</a>” tests to measure the distance between two histograms. For example the <a href="http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test">chi-squared test</a> is one of those. We are going to use a slight variation of it, called <em>quadratic-form distance.</em> It is pretty effective in our case because it reduces the importance of differences between large peaks.<br />The test is defined as follows (p and q are the two histograms we are comparing):</p>
\(distQF(p, q) = \frac{1} {2}&nbsp; \sum_{i=0}^n \frac{(p_i – q_i)^2} {p_i + q_i}\)
<p>&nbsp;</p>
<p>the implementation is straightforward:</p>
<div id="gist-2584176" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">let</span> <span class="n">quadFormDistance</span> <span class="o">(</span><span class="n">hist1</span> <span class="o">:</span> <span class="kt">float</span> <span class="kt">array</span><span class="o">)</span> <span class="o">(</span><span class="n">hist2</span> <span class="o">:</span> <span class="kt">float</span> <span class="kt">array</span><span class="o">)</span> <span class="o">=</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">Array</span><span class="p">.</span><span class="n">map2</span> <span class="o">(</span><span class="k">fun</span> <span class="n">pi</span> <span class="n">qi</span> <span class="o">-&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="n">pi</span> <span class="o">=</span> <span class="mi">0</span><span class="o">.</span> <span class="o">&amp;&amp;</span> <span class="n">qi</span> <span class="o">=</span> <span class="mi">0</span><span class="o">.</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">then</span> <span class="mi">0</span><span class="o">.</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">else</span> <span class="mi">0</span><span class="o">.</span><span class="mi">5</span> <span class="o">*</span> <span class="o">(</span><span class="n">pown</span> <span class="o">(</span><span class="n">pi</span> <span class="o">-</span> <span class="n">qi</span><span class="o">)</span> <span class="mi">2</span><span class="o">)</span> <span class="o">/</span> <span class="o">(</span><span class="n">pi</span> <span class="o">+</span> <span class="n">qi</span><span class="o">))</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">hist1</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">hist2</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="nn">Array</span><span class="p">.</span><span class="n">sum</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2584176/e0977dfa8227c9e559c1d02844a6e3db7c83c99f/qfd.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2584176#file_qfd.fs" style="float:right;margin-right:10px;color:#666">qfd.fs</a>
            <a href="https://gist.github.com/2584176">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The more two histograms are different, the larger is the return value of this test. The test returns 0 for two identical histograms.</p>
<p>A more sophisticated option is the <a href="http://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence">Jensen-Shannon divergence</a>, that is a&nbsp; a smoothed version of the <a href="http://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback-Leibler divergence</a>. While being more complicated, it has the interesting property that its square root is a <a href="http://en.wikipedia.org/wiki/Metric_(mathematics)">metric</a>, i.e. it defines a metric space (in layman&#8217;s terms, a space where the distance between two points can be measured, and where the distance A &rarr; B &rarr; C cannot be shorter than the direct distance A &rarr; B). This property is going to be useful in the next post when we’ll optimize our search algorithm.</p>
<p>The Kullback-Leibler and Jensen-Shannon divergences are defined as:</p>
\(distKL(p, q) = \sum_{i=0}^n p_i ln \frac {p_i} {q_i}\)
<p>&nbsp;</p>
\(distJS(p, q) = \frac{1}{2} distKL(p, \frac{1}{2}(p + q)) + \frac{1}{2} distKL(q, \frac{1}{2}(p + q))\)
<p>&nbsp;</p>
<p>This is the corresponding F# code:</p>
<div id="gist-2584548" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">let</span> <span class="nc">KullbackLeiblerDist</span> <span class="n">p</span> <span class="n">q</span> <span class="o">=</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">Array</span><span class="p">.</span><span class="n">map2</span> <span class="o">(</span><span class="k">fun</span> <span class="n">pi</span> <span class="n">qi</span> <span class="o">-&gt;</span> </div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="n">pi</span> <span class="o">=</span> <span class="mi">0</span><span class="o">.</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">then</span> <span class="mi">0</span><span class="o">.</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">else</span> <span class="n">pi</span> <span class="o">*</span> <span class="n">log</span> <span class="o">(</span><span class="n">pi</span> <span class="o">/</span> <span class="n">qi</span><span class="o">))</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">p</span> <span class="n">q</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="nn">Array</span><span class="p">.</span><span class="n">sum</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="k">let</span> <span class="nc">JensenShannonDist</span> <span class="n">p</span> <span class="n">q</span> <span class="o">=</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">m</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">map2</span> <span class="o">(</span><span class="k">fun</span> <span class="n">pi</span> <span class="n">qi</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">pi</span> <span class="o">+</span> <span class="n">qi</span><span class="o">)</span> <span class="o">/</span> <span class="mi">2</span><span class="o">.)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">p</span> <span class="n">q</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">(</span><span class="nc">KullbackLeiblerDist</span> <span class="n">p</span> <span class="n">m</span><span class="o">)</span> <span class="o">/</span> <span class="mi">2</span><span class="o">.</span> <span class="o">+</span> <span class="o">(</span><span class="nc">KullbackLeiblerDist</span> <span class="n">q</span> <span class="n">m</span><span class="o">)</span> <span class="o">/</span> <span class="mi">2</span><span class="o">.</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'><span class="k">let</span> <span class="n">distance</span> <span class="n">p</span> <span class="n">q</span> <span class="o">=</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">sqrt</span> <span class="o">(</span><span class="nc">JensenShannonDist</span> <span class="n">p</span> <span class="n">q</span><span class="o">)</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2584548/66f8bd27d550af7c12509fe4d6d2ae1e07ed38e5/jsd.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2584548#file_jsd.fs" style="float:right;margin-right:10px;color:#666">jsd.fs</a>
            <a href="https://gist.github.com/2584548">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><a href="http://www.cs.huji.ac.il/~ofirpele/publications/ECCV2010.pdf">This paper</a> includes an interesting comparison of various distance functions.</p>
<p>At this point our problem is almost solved. All we have to do is iterating through all the samples measuring the distance between query and sample and selecting the histogram with the smallest distance:</p>
<div id="gist-2584690" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">/// Returns the histogram closest to the given one.</span></div><div class='line' id='LC2'><span class="k">let</span> <span class="n">nearestNeighbor</span> <span class="n">sample</span> <span class="n">samples</span> <span class="o">=</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">samples</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">map</span> <span class="o">(</span><span class="k">fun</span> <span class="n">s</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="nc">FileName</span><span class="o">,</span> <span class="n">distance</span> <span class="n">s</span><span class="o">.</span><span class="nc">Data</span> <span class="n">sample</span><span class="o">.</span><span class="nc">Data</span><span class="o">))</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">sortBy</span> <span class="o">(</span><span class="k">fun</span> <span class="o">(</span><span class="n">fn</span><span class="o">,</span> <span class="n">dist</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">dist</span><span class="o">)</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">head</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|&gt;</span> <span class="n">fst</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2584690/0e89b3eac0fc07a7b8317d149a4031cc81d6d3d4/nnn.fs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2584690#file_nnn.fs" style="float:right;margin-right:10px;color:#666">nnn.fs</a>
            <a href="https://gist.github.com/2584690">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Notice that I use <em>head</em> because I’m only interested in the best matching item. I could truncate the list at any given length to obtain <em>n</em> matching items in order of relevance.</p>
<h2>Optimizing the search</h2>
<p>Maybe you’ve noticed one detail: for every query, we need to walk the full database computing the distance function between our query histogram and each image. Not very smart. If&nbsp; the database contains billions of images that’s not going to be a very fast search. Also if we perform a large number of queries in a short time we are going to be in trouble.</p>
<p>If you expected a quick and easy answer to this issue I&#8217;m going to disappoint you. However, the good news is that this problem is very interesting, much more so than it may look at first sight. This will be the topic of the next post, where I’ll write about VP-Trees, BK-Trees, and Locality-Sensitive Hashing.</p>
<h2>Grab the source</h2>
<p>The complete F# source of this tutorial <a href="https://github.com/FrancescoDeVittori/VisualSearch">is available on GitHub</a> (a whopping 132-lines of code).</p>
<p><em>Thanks to my brother Lorenzo for the review and feedback.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2012/05/simple-color-based-search-by-image-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Like structs on the stack</title>
		<link>http://www.frenk.com/2012/03/like-structs-on-the-stack/</link>
		<comments>http://www.frenk.com/2012/03/like-structs-on-the-stack/#comments</comments>
		<pubDate>Thu, 01 Mar 2012 20:43:00 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Software in general]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=412</guid>
		<description><![CDATA[&#160; &#160; I&#8217;ve seen things you people wouldn&#8217;t believe. Source code copied and pasted several times. I watched user interface events glitter in the dark down to the business logic. All those lines will be lost in time&#8230; like structs on the stack. Time to die. &#160; &#160;]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p>&nbsp;</p>
<blockquote><p><em>I&#8217;ve seen things you people wouldn&#8217;t believe. Source code copied and pasted several times. I watched user interface events glitter in the dark down to the business logic. All those lines will be lost in time&#8230; like structs on the stack.</em></p>
<p><em>Time to die.</em></p>
</blockquote>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2012/03/like-structs-on-the-stack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Real world F#: my experience (part two)</title>
		<link>http://www.frenk.com/2012/01/real-world-f-my-experience-part-two/</link>
		<comments>http://www.frenk.com/2012/01/real-world-f-my-experience-part-two/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 10:24:11 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software in general]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=376</guid>
		<description><![CDATA[The second project I recently completed in F# is a completely different animal. While the first one is a pet project I’ve put together in my spare time (with no deadline at all), this one has been a full-time work for my company (for this reason I cannot disclose some details or share source code). [...]]]></description>
			<content:encoded><![CDATA[<p>The second project I recently completed in F# is a completely different animal. While <a href="http://www.frenk.com/2012/01/real-world-f-my-experience-part-one/">the first one</a> is a pet project I’ve put together in my spare time (with no deadline at all), this one has been a full-time work for my company (for this reason I cannot disclose some details or share source code). Additionally, time available was limited. Very limited. Like <em>2 weeks</em> limited. That’s 10 working days plus a 2-days emergency buffer.</p>
<h2>A load simulator tool</h2>
<p>My company produces a high performance client-server platform that ships with our own proprietary database engine. After some important changes to the server and database codebase, we needed to test the system’s behavior under heavy load, i.e. when a large number of users are connected and firing queries.</p>
<p>As you can guess, hiring and coordinating hundreds of people to load the system the way you need is very impractical, if possible at all. Maybe it’s doable if you have your own Army of Clones, but we don’t have one, so we had to somehow automate the process. Keep in mind that the server interface is proprietary, i.e. it’s not http, SQL, or anything similar: we have to go through our library and API to access the server. For that reason we could not use any existing tool.</p>
<p>The application I was going to build was meant for internal use but it was clear that something usable by non-über-geeks would have been nice to have at some point (for example to help sizing hardware for large customers). Anyways, being the deadline very close, it was imperative (no pun intended) to focus on the most important stuff.</p>
<h2>Writing your own DSL</h2>
<p>I decided to define an external <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSL</a> to describe the simulation scenarios. The language would let you express the creation of users, connections, queries, pauses, etc. in a simple way.<br />
The second decision was to use F#. Fortunately nobody objected (again no pun intended). I was to work on the project alone, so I could basically use whatever I liked.</p>
<p>Once I defined the grammar I went to step 2, i.e. parsing. Obviously I was not going to reinvent the wheel by rolling out my own lexer and parser so the choice was between parser generators (FsLex/FsYacc, Irony for C# &amp; co.) and <a href="http://en.wikipedia.org/wiki/Combinator_library">combinator libraries</a> à la <a href="http://www.quanttec.com/fparsec/">FParsec</a>. After taking some advice from the great F# community on Twitter (thanks <a href="http://strangelights.com/blog">Robert</a>!), I opted for FParsec. I admit it looked a bit intimidating, but the idea of not introducing a tooling step in the build process was appealing, plus I had never used a combinator library before and was curious.</p>
<p>Here starts the amazement. As mentioned, at first FParsec looks slightly cryptic, but once you get the main concepts and get over a few gotchas it just “clicks”. You quickly reach a point where reading the parser code is almost like reading the grammar definition. Making changes is a matter of a few minutes with a very low risk of introducing new errors. FParsec gives you an enormous flexibility and even if the learning curve is steeper than learning parser generators I suggest you look at it if you’ve never done it before. The official documentation is great too.</p>
<p>Anyways, in a few days I had a parser that lifted the input program to the abstract syntax tree. Sweet!</p>
<p><em>Note</em>: in case you are wondering, the language I defined was not super complicated but also not trivial. It supports regular loops as well as parallel ones (iterations are executed in parallel), nested loops and a plethora of options on all the various commands. I opted for a rich syntax that results in programs that are almost written in natural language. I cannot disclose all the details, but you can get an idea by looking at the screenshots.</p>
<p><a href="http://www.frenk.com/wp-content/uploads/2012/01/Capture4.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Capture4" src="http://www.frenk.com/wp-content/uploads/2012/01/Capture4_thumb.png" border="0" alt="Capture4" width="228" height="244" /></a></p>
<h2>Walking the tree</h2>
<p>Second amazement: thanks to discriminated unions and pattern matching, walking the syntax tree is an incredibly fluid and easy process. The code is so compact and elegant that I keep opening that file just to look at it. No boilerplate, no class proliferation, no wasted characters. Just <em>the</em> code.</p>
<p>Unfortunately I could not leverage the powerful F# concurrency features to run parallel loops because the client library that interfaces with our server is not thread-safe, so all I could do was starting new threads with each its own separate AppDomain. My skills on asynchronous workflows &amp; co. are still limited so I don’t know if there’s a better way. If that’s the case, I’d love to hear your feedback in the comments.</p>
<h2>GUI and extras</h2>
<p>With parsing and interpreting done, the bulk of the job was over. I just needed to add logging and a less geeky interface than the command line. With room to spare, I created a WPF GUI that controls the execution and reads logs to display status and stats. This was nothing particularly exotic, but I was able to fit in some nice touches like a graphical timeline to represent operations executed on the different threads. I wrote the GUI in XAML/C# using MVVM-Light. The parser/interpreter runs in a separate process, so that in case of a crash (not a remote possibility when you are pushing the hardware limits) the GUI keeps running and tells you what happened.</p>
<p><a href="http://www.frenk.com/wp-content/uploads/2012/01/Capture3.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Capture3" src="http://www.frenk.com/wp-content/uploads/2012/01/Capture3_thumb.png" border="0" alt="Capture3" width="239" height="244" /></a></p>
<p>So 10 days had passed and this is what had been done:</p>
<ul>
<li>the DSL grammar definition</li>
<li>a parser and an interpreter for it. It took slightly more than necessary because I had to learn FParsec along the way (<a href="http://strangelights.com/blog/archive/2011/11/04/the-combinator-approach-to-programming-domain-specific-languages-with-f.aspx">this talk</a> by Robert Pickering has been very helpful).</li>
<li>a GUI with some bells and whistles</li>
</ul>
<p>plus some extras (that as you know better than me, are very time consuming):</p>
<ul>
<li>a (admittedly basic) distributable package</li>
<li>the syntax highlighting definition for Notepad++ <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://www.frenk.com/wp-content/uploads/2012/01/wlEmoticon-smile.png" alt="Smile" /></li>
<li>several code samples that show the DSL capabilities</li>
<li>the user manual and language specification (I got some help with that)</li>
<li>a tutorial</li>
</ul>
<p>Developing the GUI and producing the extras went at normal speed, but I’m positive that writing this parser and interpreter in C# would have taken me close to the ten days alone. Maybe my standards are low, I don’t know, but I’m honestly blown away by what I could achieve in such a short time. Also notice that I’m much more experienced in C# than in F#.</p>
<p>Truth to be told, I had another advantage: this project was done in the year ending period when several people are on holidays and the office is very quiet. I also put in some late evenings, but I have a family with two kids, I just cannot code 24*7 even if I wanted.</p>
<h2>The stars of the show</h2>
<p>The goal of this post is not telling the world how fast I work. It’s impossible for anyone to judge if a project would have needed 2 or 100 days without knowing all the details. No, I’m writing this because <em>I</em> know all the details and I know that F# gave me a huge advantage. Much more so than I imagined when I started.</p>
<p>These are things that I think make F# ideal for a project like this:</p>
<h3>Higher order functions</h3>
<p>These are what allow libraries like FParsec to exist, amongst the rest.</p>
<h3>Discriminated unions, tuples and pattern matching</h3>
<p>This trio is worth alone the price of entry. They make for very terse code and bring other great advantages on the table as well.</p>
<h3>It works the first time</h3>
<p>I still don’t get why it is so. Maybe it’s because of the lack of <em>null</em>s. Maybe it’s because (as I’ve written in part one) I think functional programming forces you to think more and write/debug less. The net result is that when I write F# I mostly get it right the first time. Because of the higher-order functions there are less corner cases that suddenly appear and crash everything.</p>
<p>Now most of these features are available in several functional languages, however the seamless .NET integration was fundamental in my case (the libraries I had to use are .NET), and some F#-only constructs make coding fun and speedy at the same time.</p>
<h2>Conclusion</h2>
<p>If you’re not living under a rock (like I’m <em>literally</em> doing right now –but that’s another story) you’ve sure heard of F#. Maybe you’ve even seen some examples, but as I’ve heard many times from C# developers, they looked incomprehensible. Don’t let that stop you, it’s just not true. If you&#8217;re new to functional programming it looks that way because F# is (mostly) a functional language, i.e. you’re not only learning a new language, you’re learning a new paradigm. A different way of thinking of your programs. It does take some effort, for sure. Is it worth it? It’s up to you to decide. To me, getting back to functional programming with F# after several years of OOP/C# has been a real breath of fresh air.</p>
<p>If you decide to learn more, here are some great places to start:</p>
<p><a href="http://richardminerich.com/2011/10/advice-for-getting-started-with-f/">Advice for getting started with F#</a> by Richard Minerich<br />
<a href="http://blogs.msdn.com/b/doriancorompt/archive/2012/01/08/an-overview-of-functional-programming.aspx">An overview of functional programming</a> by Dorian Corompt (<a href="http://blogs.msdn.com/b/doriancorompt/archive/2012/01/08/1-recursion-where-are-my-for-while-loops.aspx">recursion</a>, <a href="http://blogs.msdn.com/b/doriancorompt/archive/2012/01/13/2-list-cons-car-cdr-amp-co.aspx">lists</a>, more to come…)</p>
<p>I suggest starting with the basics: you can already accomplish a lot with just lists, sequences, tuples, unions and pattern matching. When you feel ready you can move on to the more advanced topics.<br />
Have fun!</p>
<p><em>Again, many thanks to <a href="http://www.navision-blog.de">Steffen</a> and <a href="http://gissolved.blogspot.com/">Samuel</a> for the feedback!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2012/01/real-world-f-my-experience-part-two/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Real world F#: my experience (part one)</title>
		<link>http://www.frenk.com/2012/01/real-world-f-my-experience-part-one/</link>
		<comments>http://www.frenk.com/2012/01/real-world-f-my-experience-part-one/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 14:50:23 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Computer]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=382</guid>
		<description><![CDATA[I’ve been playing with F# on and off for about one year, but only recently I was able to complete a few “real world” projects. I was so impressed that I decided to share my experience. In this two-part series I will talk about two very different projects to give you an idea of how [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been playing with F# on and off for about one year, but only recently I was able to complete a few “real world” projects. I was so impressed that I decided to share my experience. In this two-part series I will talk about two very different projects to give you an idea of how wide the spectrum of applications is where F# feels right at home.</p>
<h2>The first project</h2>
<p>The first project is named VeloSizer. You can <a href="http://velosizer.frenk.com">check it out here</a> (I may release it as open source but I’m still undecided on what to do with it). I assume you are not a cycling geek so I’ll spare you the details, but in short this application computes the bike setup given your position and the frame geometry. If you’re interested there’s a detailed description on the application page. Surprisingly enough, I’ve never found anything that does this very thing (except for full blown and expensive CADs), so I decided to write it myself.</p>
<p><a href="http://www.frenk.com/wp-content/uploads/2012/01/velosizer.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="velosizer" src="http://www.frenk.com/wp-content/uploads/2012/01/velosizer_thumb.png" border="0" alt="velosizer" width="244" height="229" /></a></p>
<p>The application is built in Silverlight: the XAML frontend is basically a glorified input form. It’s not particularly complex, some details are more complicated than it may look at first sight, but still there’s nothing extraordinary. I took a rather standard approach and employed the MVVM pattern (using <a href="http://mvvmlight.codeplex.com/">MVVM-Light</a>) for a clear separation of concerns. The View Model is C# while the Model –where the interesting stuff happens– is written in F#.</p>
<p>Solving this particular problem does not require very complicated mathematics, but involves a large number of geometrical operations (trigonometry and the likes). Without abstracting and hiding away all the math, the solution quickly becomes a nightmare that spirals out of control (don’t ask how I know). For this reason I’ve implemented a simple 2D CAD engine that sits at the application core.</p>
<h2>How it went</h2>
<p>Here are some things I noticed while using F# in a “real” project for the first time.</p>
<h3>Units of measure</h3>
<p>F#’s support for units of measures built straight into the type system has been very helpful to avoid stupid errors like mixing degrees with radians with millimeters, etc. It is really a plus when dealing with physical dimensions.</p>
<h3>Conciseness</h3>
<p>The language syntax is very light and unobtrusive, which makes it ideal to write mathematically-oriented code. The main benefit to me has been that the math stands out clearly, without parenthesis, type annotations or artifacts that make things harder to read. Also writing the code is a joy: you can really focus on the reasoning and almost forget that you are actually programming. In fact translating the equations written on paper to code is almost copy &amp; paste.</p>
<h3>Testability</h3>
<p>I heartily agree with Richard Minerich when he says that <a href="http://richardminerich.com/2012/01/why-do-most-programmers-work-so-hard-at-pretending-that-theyre-not-doing-math/">testing does not replace a strong, theoretically-validated model</a>. It’s the very same reason that pushed me to build most of this application’s engine on paper before writing a line of code. However I still make (lots of) mistakes when implementing a model –regardless of how correct it is– so I feel safer with the additional support of a solid testing framework.<br />
The nature of functional programming makes it an ideal target for unit tests. Short, side-effects free functions are a joy to test. Result: it has been very easy to create a nice safety net in form of an NUnit project.<br />
I must admit I would probably have written this library more or less using the same style in C#, but in functional programming this is <em>the default</em>.</p>
<h3>Interoperatibily with C#/GUI</h3>
<p>This is somewhat of a sore point. I don’t know if it is due to my lack of experience (likely) or the nature of a GUI-driven application, but I’ve ended up with many mutable (and not very idiomatic in general) classes, for two main reasons:</p>
<ul>
<li>I had to persist the business objects (using the <a href="http://sterling.codeplex.com/">Sterling</a> NoSQL database) and all the serializers for Silverlight need public setters as they are not allowed to use reflection.</li>
<li>With MVVM, each View is bound to its respective View Model, which is nothing more than a wrapper around its respective business object defined in the model (F#).<br />
Now when for instance the user changes a value in a TextBox, the new value is propagated to the View Model, which in turns propagates it to the Model. You can tell it’s not very practical to create a new instance of the model every time a value changes, so immutable objects do not adapt so well to the situation.</li>
</ul>
<p>This means that the business objects are very C#-like. They still benefit from the lighter syntax, type inference, etc…, but they don’t fully leverage the power of the language. Fortunately the “application brain” does not suffer much from this.</p>
<p>Is this due to MVVM, XAML and in general GUI patterns being oriented towards the object-oriented paradigm? I don’t know. I’ve heard of a GUI framework specifically written for F#, but I don’t know much more.<br />
I would be very interested to hear your opinion on this subject.</p>
<p><em>Note: as Stephen points out, keeping the model immutable may not be so much of a problem. I’ll give it a try.</em></p>
<h3>Guidance and community support</h3>
<p>The F# community is still small, but it more than makes up for it in quality. The active users on <a href="http://stackoverflow.com">Stackoverflow</a> and other sites are <em>extremely</em> competent. It’s rare to get bogus answers or to get stuck on a problem for long.<br />
What I’ve found difficult though is getting guidance. I often ask myself if my code is well written or a pile of junk. I suppose the only solution is to refine my own sense by reading other people’s code.</p>
<h3>Intellisense</h3>
<p>Visual Studio’s Intellisense for C# is spectacular and has made us very lazy. F# support is much better than it was at the beginning, but it’s still not up to the same level of C#. In the end though it’s only lacking a few details like parameter names or support for the pipeline operator –the next release already includes some improvements in this area.</p>
<h3>Debugging</h3>
<p>Setting breakpoints and watching state change is not simple in functional code because (usually) there is <em>no state</em>. If you debug a lot, this may be a bit unsettling at first, but then you realize it is not so much of a drawback. It is <em>a benefit</em> in fact. Breakpoints are evil: building a half-working solution, running it through breakpoints and tune it until the result matches what you expect is very close to the definitions of <a href="http://blogs.msdn.com/b/ericlippert/archive/2004/03/01/82168.aspx">cargo-cult programming</a>/<em>programming by coincidence</em>.<br />
It is my opinion that functional programming makes you <em>think more and write/edit/debug less</em>. I believe this has made me a better developer because I now tend to stop, think about the solution “offline” and only write it down when I get it.</p>
<h3>Productivity</h3>
<p>I can’t give any judgment on productivity because this application has been a pet project I’ve built alone without any deadline, working literally 15 minutes at a time. We recently welcomed another family member, which has made things even harder. Anyways it took me about 7 months to complete this project, but it’s very hard for me to tell if F# has given any productivity boost at all. More on this in part two.</p>
<h2>Conclusion</h2>
<p>It has been a real pleasure to write the F# part of this application. When you look at the application source, the first things that jumps to the eye is that the View Model (C#/OO) is <em>way</em> larger (in lines of code) than the model (F#/mostly functional), yet it only does “stupid” things: it’s almost exclusively made of property definitions, RaisePropertyChanged events, brackets, etc. It is like a very large box full of bubble wrap sheet, with only a small, precious gift in the middle.</p>
<p>That said I’ve been left with the impression that I haven’t used all of the language’s power. Writing the View Model in F# would only have slightly alleviated its ineffectiveness, what I need is probably a different pattern for GUI interaction.</p>
<p>In part two I’ll talk about a very different (and more interesting) project, where F# really shined. In the mean time I would be very interested to hear your opinions.</p>
<p><em>Thanks a lot to </em><a href="http://www.navision-blog.de"><em>Steffen Forkmann</em></a><em> and </em><a href="http://gissolved.blogspot.com/"><em>Samuel Bosch</em></a><em> for proof reading and general feedback!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2012/01/real-world-f-my-experience-part-one/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>When to unit test private methods?</title>
		<link>http://www.frenk.com/2011/11/when-to-unit-test-private-methods/</link>
		<comments>http://www.frenk.com/2011/11/when-to-unit-test-private-methods/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 10:29:31 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[Software in general]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test driven development]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=369</guid>
		<description><![CDATA[in TDD you are often confronted with the question “should I restrict my unit test to public methods or include private ones as well?”. There isn’t a widely accepted consensus and there are many articles around on the subject. I’ve been thinking about it recently and this is my take on it. A class’ public [...]]]></description>
			<content:encoded><![CDATA[<p>in TDD you are often confronted with the question “should I restrict my unit test to public methods or include private ones as well?”.</p>
<p>There isn’t a widely accepted consensus and there are many articles around on the subject. I’ve been thinking about it recently and this is my take on it.</p>
<p>A class’ public interface is a <em>contract</em> between the class and its users. When you test a class’ public interface you are trying to ensure that it respects the terms of the contract. So testing a public interface is technically enough to ensure that your program is correct (within the scope of unit testing of course, not in a general sense).</p>
<p>Generally nobody cares how your class is internally implemented as long as it works as advertised. Private members are an implementation detail and are used by public members anyways (otherwise you could just delete them), so tests on the public interface cover private members as well.</p>
<p>However, tests on private methods have a benefit: they can help you spot errors closer to where they are originated. You can see it this way: <strong>tests on public methods tell you that <em>something went wrong,</em> while tests on private methods can tell you <em>where something went wrong</em></strong>. In other words they bring some comfort.</p>
<p>While additional comfort is nice to have, it always comes at a cost. These are the main costs you’ll assume when deciding to test private members:</p>
<ul>
<li>You’ll have to write more tests.</li>
<li>Maintenance becomes quite stressful as you’ll be changing/adding/removing several tests every time you make a change in a class implementation.</li>
<li>You miss the benefits of LDD (Laziness-Driven Development –invented by myself, don’t bother looking in wikipedia). In short, if a developer must write tests for public members only, she will keep them private unless really necessary, just because it takes less work. And keeping the public interface as narrow as possible <a href="http://c2.com/cgi/wiki?NarrowTheInterface">is a good thing</a>.</li>
</ul>
<p>In order to answer the original question you’ll have to decide if the benefits are greater than the costs.</p>
<p><strong>Personally, I only test public members and occasionally make an exception for private members that produce values difficult to verify at a glance.</strong></p>
<p><strong> </strong>When you combine the output of methods that produce “obvious values” it’s generally easy to spot what went wrong (a null reference, an incompletely initialized object, a wrongly formatted string, etc.). On the other hand, when methods generate for ex. floating point values, it’s difficult to quickly tell if something is wrong, thus it’s difficult to understand what caused a test to fail.</p>
<p>For example, I have a public <span style="font-family: 'Courier New';">GetPlexoidMass()</span> function that computes the mass of a plexoid using a complex formula based on sine and cosine*. It made sense for me to test the private <span style="font-family: 'Courier New';">Sin</span> and <span style="font-family: 'Courier New';">Cos</span> functions as well, so that when a test for <span style="font-family: 'Courier New';">GetPlexoidMass</span> turns red it takes me less time to figure out what caused the error without debugging every single step in the formula. The intermediate results inside <span style="font-family: 'Courier New';">GetPlexoidMass</span> are floating point numbers and it’s otherwise difficult to understand which one is wrong without an accurate and time-consuming analysis.</p>
<p>This is a case you often find in number manipulation and/or mathematical-intensive libraries, usually found at an application’s core. This kind of function is harder to find the more you move towards the application surface. I would go as far as saying that feeling the constant need to test private members near the application surface may be a <a href="http://en.wikipedia.org/wiki/Code_smell">code smell</a> and could indicate a problem in the application layering.</p>
<p>I hope these elements may help you make the right choice. If you have other criteria or considerations please let discuss in the comments!</p>
<p>&nbsp;</p>
<p><span style="font-size: x-small;"><em>* dummy example of course</em></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/11/when-to-unit-test-private-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight unit testing with NUnit: yes you can (without hacks)!</title>
		<link>http://www.frenk.com/2011/11/silverlight-unit-testing-with-nunit-yes-you-can-without-hacks/</link>
		<comments>http://www.frenk.com/2011/11/silverlight-unit-testing-with-nunit-yes-you-can-without-hacks/#comments</comments>
		<pubDate>Wed, 02 Nov 2011 09:49:59 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[Silverlight4]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=361</guid>
		<description><![CDATA[It may be obvious for most of you, but it took a while to my caveman brain to realize this, so I figured I could post it for other cavemen. You (we) have got an excuse though: the short release cycle of Silverlight means that most stackoverflow questions and blog posts on the subject are [...]]]></description>
			<content:encoded><![CDATA[<p>It may be obvious for most of you, but it took a while to my caveman brain to realize this, so I figured I could post it for other cavemen. You (we) have got an excuse though: the short release cycle of Silverlight means that most <a href="http://stackoverflow.com">stackoverflow</a> questions and blog posts on the subject are out-of-date and refer to older versions of Silverlight (&lt;=3) when what I describe was not possible.</p>
<p>Up to Silverlight 3 you had to use a Silverlight-specific unit testing tool, like the <a href="http://silverlight.codeplex.com">Silverlight Toolkit framework</a>. These tools are quite awesome and have been fundamental, but it’s nice to have the full power of <a href="http://www.nunit.org/">NUnit</a> (or <a href="http://xunit.codeplex.com/">xUnit</a> &amp; co.) at disposal. In addition to the community and tooling support, it’s practical to use the same tool you already use for other .NET projects.</p>
<p>The game changer is called <em>binary assembly compatibility</em>, brought by Silverlight 4. In a few words this means that you can add a reference to a Silverlight assembly from a “full” .NET project (provided that you don’t use any Silverlight-only class).</p>
<p>If your application is correctly layered (for ex. with MVVM) in most cases it’s trivial to keep views and viewModels/models in separate assemblies. ViewModels and models usually don’t reference any Silverlight-only class (otherwise you may have a code smell!) and are 100% compatible with .NET, so testing them with NUnit is as easy as</p>
<ul>
<li>create a .NET class library in your solution</li>
<li>add a reference to NUnit (<a href="http://nuget.org/">NuGet</a> it!)</li>
<li>add a reference to your model and/or viewModel assemblies</li>
<li>write your unit tests</li>
<li>run them with NUnit</li>
</ul>
<p>no tweaking or hacking required and works fine with F# assemblies as well.</p>
<p>It is typical for views to use Silverlight-only classes, but this is generally not a problem because it doesn’t make much sense to unit-test them anyways as they are mostly XAML with very little amounts of code-behind.</p>
<p>Free tip: if you want to test internal classes and methods you can add the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=VS.95).aspx">InternalsVisibleTo attribute</a> to the target assembly.</p>
<p>Happy testing!</p>
<p><a href="http://www.frenk.com/wp-content/uploads/2011/11/bear.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="bear" src="http://www.frenk.com/wp-content/uploads/2011/11/bear_thumb.jpg" border="0" alt="bear" width="571" height="482" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/11/silverlight-unit-testing-with-nunit-yes-you-can-without-hacks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic member binding in Silverlight 4</title>
		<link>http://www.frenk.com/2011/10/dynamic-member-binding-in-silverlight-4/</link>
		<comments>http://www.frenk.com/2011/10/dynamic-member-binding-in-silverlight-4/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 20:00:36 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Computer]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[dynamics]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[silverlight 4]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=343</guid>
		<description><![CDATA[UPDATE: Xavier Decoster already wrote a nice article on this topic some time ago. Please check it out! (Note to self: improve google skills) First, let me say that I’ll take the long route, so if you are already familiar with dynamic typing in C# you can probably jump straight to the last section. Otherwise [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE</strong>: <em>Xavier Decoster already wrote a nice article on this topic some time ago. Please <a href="http://www.xavierdecoster.com/post/2010/10/08/Silverlight-4-Data-Binding-to-Dynamic-DataContext.aspx">check it out</a>! (Note to self: improve google skills)</em></p>
<p>First, let me say that I’ll take the long route, so if you are already familiar with dynamic typing in C# you can probably jump straight to the last section. Otherwise read on, you may learn something cool that is not used every day but can save you in some situations.</p>
<p>In the [not so] old days of Silverlight 3 if you wanted to dynamically create a class you had to emit intermediate language instructions, etc. Definitely not so easy. Silverlight 4 (with C# 4.0) introduced <a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx">support for dynamics</a> and simplified this a lot.</p>
<p>Straight from the <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx">DynamicObject documentation</a>, this simple implementation of a dynamic dictionary uses an internal dictionary to store string/object pairs where the key is the member name and value is its associated value.</p>
<pre class="brush: c-sharp">
public class DynamicDictionary : DynamicObject
{
    Dictionary&lt;string, object&gt; dictionary =
        new Dictionary&lt;string, object&gt;();

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
}
</pre>
<p>In a DynamicObject you have two methods (<em>TryGetMember</em> and <em>TrySetMember</em>) that are invoked every time someone tries to access the objects’ members. In this particular implementation, when this code is executed</p>
<pre class="brush: c-sharp">
dynamic myDynamicObject = new DynamicDictionary();
myDynamicObject.FirstName = &quot;John&quot;;
myDynamicObject.Age = 18;
</pre>
<p>two pairs &#8220;FirstName&#8221;/&#8221;John&#8221; and &#8220;Age&#8221;/18 are stored in the internal dictionary. On the other hand when you do</p>
<pre class="brush: c-sharp">
string test = myDynamicObject.FirstName;
</pre>
<p>instead of calling the getter of FirstName (like any statically typed object would do), <em>TryGetMember</em> is invoked and the value corresponding to key “FirstName” is looked up from the internal dictionary.</p>
<p>The <em>dynamic</em> keyword tells the compiler that the member will be looked up at runtime, so you can set/get any member you want and the compiler won’t complain: he knows the members will be resolved while the program is running.</p>
<h2>The binding problem</h2>
<p>Now there is only a small problem with this approach (and it’s the whole point of this post): if you create a binding that targets a dynamic member you’ll get an error. It looks like the Silverlight binding engine “cannot discover” dynamic properties.</p>
<p>For example this does not work:</p>
<pre class="brush: c-sharp">
public dynamic MyDynamicDictionary {  get;     set; }

// ...

MyDynamicDictionary = new DynamicDictionary();
MyDynamicDictionary.Label = &quot;Hello, I&#039;m dynamic!&quot;;
</pre>
<pre class="brush: xml"> &lt;Button Content=&quot;{Binding MyDynamicDictionary.Label}&quot;/&gt; </pre>
<p><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="brokenBinding" src="http://www.frenk.com/wp-content/uploads/2011/10/brokenBinding_thumb.png" border="0" alt="brokenBinding" width="175" height="60" /></p>
<p>If you look at the output:</p>
<pre>System.Windows.Data Error: BindingExpression path error: 'Label' property not found on 'SilverlightApplication22.DynamicDictionary'</pre>
<h2>Indexed binding to the rescue</h2>
<p>Telerik’s Vladimir Enchev <a href="http://blogs.telerik.com/blogs/posts/11-09-28/dynamic-binding-for-your-silverlight-applications.aspx">explains on his blog</a> how this approach can be used to implement a dataTable-like structure that can back for ex. a datagrid. The clever bit is that he added to the DynamicDictionary the [] indexer:</p>
<pre class="brush: c-sharp">
public object this[string columnName]
{
    get
    {
        if (dictionary.ContainsKey(columnName))
            return dictionary[columnName];
        return null;
    }
    set
    {
        if (!dictionary.ContainsKey(columnName))
        {
            dictionary.Add(columnName, value);
            RaisePropertyChanged(columnName);
        }
        else
        {
            dictionary[columnName] = value;
            RaisePropertyChanged(columnName);
        }
    }
}
</pre>
<p>Now we have two alternatives to access the dynamically-created members:</p>
<pre class="brush: c-sharp">
// like before:
dynamic myDynamicObject2 = new DynamicDictionary();
myDynamicObject2.FirstName = &quot;John&quot;;
myDynamicObject2.LastName = &quot;Smith&quot;;

// using []:
var myDynamicObject3 = new DynamicDictionary();
myDynamicObject[&quot;FirstName&quot;] = &quot;John&quot;;
myDynamicObject[&quot;LastName&quot;] = &quot;Smith&quot;;
</pre>
<p>The two approaches have exactly the same effect (notice that in the second version the variable is declared with <em>var</em> instead of <em>dynamic</em>).</p>
<p>Using square brackets to access members has the advantage that you can actually create members using strings: let’s say you have a string/object dictionary, it’s easy to loop the dictionary entries and “create” a member for every key while setting the value as the member value. After this you’ll have an object that mirrors the dictionary:</p>
<pre class="brush: c-sharp">
var source = new Dictionary&lt;string, object&gt;();
source.Add(&quot;FirstName&quot;, &quot;John&quot;);
source.Add(&quot;LastName&quot;, &quot;Smith&quot;);
source.Add(&quot;Age&quot;, 18);

var target = new DynamicDictionary();
foreach (var entry in source)
    target[entry.Key] = entry.Value;
</pre>
<p>now target is the same as you would have after doing</p>
<pre class="brush: c-sharp">
new something() { FirstName = &quot;John&quot;, LastName = &quot;Smith&quot;, Age = 18 };
</pre>
<p>except that it “adapts” to any key/value you have in the dictionary. Cool eh?!</p>
<p>It turns out that the indexer has another side benefit (that solves the binding problem). In fact Silverlight 4 also introduced indexed bindings: you can create bindings that target indexed structures (like a list or a dictionary) simply using square brackets. The nice thing is that our dynamic class happens to have an indexer.</p>
<p>Let&#8217;s revisit our code: if we declare the property as <em>DynamicDictyionary</em> instead of <em>dynamic</em> (we now must set the properties using the indexer because the compiler only allows &#8220;non-existing&#8221; properties on object of <em>dynamic</em> type):</p>
<pre class="brush: c-sharp">
public DynamicDictionary MyDynamicDictionary { get; set; }

//...

MyDynamicDictionary = new DynamicDictionary();
MyDynamicDictionary[&quot;Label&quot;] = &quot;Hello, I&#039;m dynamic!&quot;;
</pre>
<p>and change the XAML to look like this (notice the square brackets)</p>
<pre class="brush: xml">
&lt;Button Content=&quot;{Binding MyDynamicDictionary2[Label]}&quot;/&gt;
</pre>
<p>the dynamic binding does work fine:</p>
<p><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="okBinding" src="http://www.frenk.com/wp-content/uploads/2011/10/okBinding_thumb.png" border="0" alt="okBinding" width="155" height="45" /></p>
<p>Happy dynamic binding!</p>
<p><a href="http://www.frenk.com/wp-content/uploads/2011/10/DynamicBindingSL4.zip">Download the code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/10/dynamic-member-binding-in-silverlight-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# runtime for Silverlight version v4.0 is not installed.</title>
		<link>http://www.frenk.com/2011/08/f-runtime-for-silverlight-version-v4-0-is-not-installed/</link>
		<comments>http://www.frenk.com/2011/08/f-runtime-for-silverlight-version-v4-0-is-not-installed/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 19:38:00 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Silverlight4]]></category>
		<category><![CDATA[visual studio 2010]]></category>

		<guid isPermaLink="false">http://www.frenk.com/2011/08/f-runtime-for-silverlight-version-v4-0-is-not-installed/</guid>
		<description><![CDATA[After playing with some Silverlight beta bits, going back to RTM, etc. I could not compile F# projects for Silverlight 4 anymore. Even after reinstalling everything in [what I think is] the right sequence I was still getting this error: F# runtime for Silverlight version v4.0 is not installed. Please go to http://go.microsoft.com/fwlink/?LinkId=177463 to download [...]]]></description>
			<content:encoded><![CDATA[<p>After playing with some Silverlight beta bits, going back to RTM, etc. I could not compile F# projects for Silverlight 4 anymore. Even after reinstalling everything in [what I think is] the right sequence I was still getting this error:</p>
<blockquote><p>F# runtime for Silverlight version v4.0 is not installed.<br />
Please go to <a href="http://go.microsoft.com/fwlink/?LinkId=177463">http://go.microsoft.com/fwlink/?LinkId=177463</a> to download and install matching F# runtime<br />
C:\Program Files (x86)\Microsoft F#\v4.0\Microsoft.FSharp.Targets</p></blockquote>
<p>I followed the link and re-installed the <em>Microsoft Silverlight 4 Tools for Visual Studio 2010</em> (which I already did), but the error was still there. Looking into <strong>c:\program files (x86)\Microsoft F#\Silverlight\Libraries\Client</strong> I noticed that the folder v3.0 was there, but not v4.0.</p>
<h2>The solution</h2>
<p>If you have the same issue, go to <a href="http://go.microsoft.com/fwlink/?LinkId=177463">http://go.microsoft.com/fwlink/?LinkId=177463</a> and download the Silverlight 4 Tools installer (Silverlight4_Tools.exe).<br />
Don’t run it, instead extract its contents with your zip tool of choice (I used WinRar) and run <strong>FSharpRuntimeSL4.msi</strong>.<br />
Now look again in <strong>c:\program files (x86)\Microsoft F#\Silverlight\Libraries\Client</strong>, a v4.0 folder should have appeared. If you have it your Silverlight 4 F# projects should now compile.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/08/f-runtime-for-silverlight-version-v4-0-is-not-installed/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7: how to reset the idle detection countdown</title>
		<link>http://www.frenk.com/2011/03/windows-phone-7-how-to-reset-the-idle-detection-countdown/</link>
		<comments>http://www.frenk.com/2011/03/windows-phone-7-how-to-reset-the-idle-detection-countdown/#comments</comments>
		<pubDate>Fri, 04 Mar 2011 18:01:25 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=328</guid>
		<description><![CDATA[Windows Phone 7 like every other phone OS turns off the screen after a period of inactivity. This is not a problem most of the time because any user activity (namely finger interactions on the screen) resets the countdown, so if you are using an application the screen saver will not get in the way. [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Phone 7 like every other phone OS turns off the screen after a period of inactivity. This is not a problem most of the time because any user activity (namely finger interactions on the screen) resets the countdown, so if you are using an application the screen saver will not get in the way. However there are some particular cases where it is useful to disable the idle detection, for example in games or apps that require long reading (or watching). In that case you can completely disable idle detection:</p>
<pre class="brush: c-sharp">
PhoneApplicationService.Current.UserIdleDetectionMode =
    IdleDetectionMode.Disabled;
</pre>
<p>Keep in mind that this disables the &#8220;screen saver&#8221; at all, so be careful because you could drain the poor user’s battery if you do it without valid reason.</p>
<p>There is another more interesting case, though: suppose your app uses the accelerometer as its main user input. In this case there won’t be any user activity to trigger a countdown reset, but disabling it at all also doesn’t look like the best idea (what if the user puts the phone on the table to go grab a beer?).</p>
<p>The best in this case would be to reset the count-down when a movement is detected, i.e. treating accelerometer events like screen user input. How to do this?</p>
<p>The answer is extremely simple: you can just disable the IdleDetection and re-enable it again. This will reset the count-down. One little caveat: you cannot re-enable it immediately after having disabled it, the OS is smart enough not to be fooled and will ignore your two commands. You’ll have to wait a short while before re-enabling idle detection.</p>
<p>Here is an example: when I get a new reading from the accelerometer (I’m using the <a href="http://windowsteamblog.com/windows_phone/b/wpdev/archive/2010/09/08/using-the-accelerometer-on-windows-phone-7.aspx">AccelerometerHelper</a>) I check if there has been a large enough movement and in that case I disable the idle detection. Otherwise I enable it –this effectively resets the countdown every time the movement goes above a given threshold. Keep in mind that the accelerometer fires 50 times per second, that’s why I used a bool field to avoid unnecessary calls to the system setting. I’m not sure this prevents an actual performance loss, but it would be worth it to experiment and measure a little if you are using this technique in your apps.</p>
<pre class="brush: c-sharp">
double _currentValue;
bool _screenSaverEnabled = true;

private void OnAccelerometerHelperReadingChanged(object sender, AccelerometerHelperReadingEventArgs e)
{
    Dispatcher.BeginInvoke(() =&gt;
        {
            // you&#039;ll have something more useful in your app
            computedValue = e.OptimallyFilteredAcceleration.X;

            var delta = Math.Abs(computedValue - _currentValue);
            if (_screenSaverEnabled)
            {
                if (delta &gt; SOME_ARBITRARY_THRESOLD)
                {
                    _screenSaverEnabled = false;
                    PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
                    Debug.WriteLine(&quot;Screen saver disabled&quot;);
                }
            }
            else
            {
                _screenSaverEnabled = true;
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
                Debug.WriteLine(&quot;Screen saver enabled&quot;);
            }
            _currentValue = computedValue;
        }
    );
}
</pre>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/03/windows-phone-7-how-to-reset-the-idle-detection-countdown/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7: correct pinch zoom in Silverlight</title>
		<link>http://www.frenk.com/2011/03/windows-phone-7-correct-pinch-zoom-in-silverlight/</link>
		<comments>http://www.frenk.com/2011/03/windows-phone-7-correct-pinch-zoom-in-silverlight/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 22:42:28 +0000</pubDate>
		<dc:creator>frenk</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://www.frenk.com/?p=317</guid>
		<description><![CDATA[Pinch zooming is one of those things that look incredibly simple until you actually try to implement them. At that point you realize it hides quite a number of intricacies that make it hard to get it right. If you tried to implement pinch zooming in Silverlight for Windows Phone 7 you probably know what [...]]]></description>
			<content:encoded><![CDATA[<p>Pinch zooming is one of those things that look incredibly simple until you actually try to implement them. At that point you realize it hides quite a number of intricacies that make it hard to get it right. If you tried to implement pinch zooming in Silverlight for Windows Phone 7 you probably know what I’m talking about.</p>
<h2>What does it means <em>getting it right</em>?</h2>
<p>Adrian Tsai already gave <a href="http://adtsai.blogspot.com/2010/09/pinch-zooming-using-xna4-on-wp7-getting.html">an excellent explanation</a>, so I won’t repeat his words. The test is extremely simple: pick two points in the image (for example two eyes) and zoom with your fingers on them. If at the end of the zoom the two points are still under your fingers you got it right –otherwise you got it wrong.</p>
<h2>Multitouch Behavior</h2>
<p>Laurent Bugnion, Davide Zordan and David Kelly are the men behind  <a href="http://multitouch.codeplex.com/">Multitouch Behavior for SL and WPF</a>. It’s an impressive open source project and you should check it out. In addition to pinch-zooming it gives you rotation, inertia, debug mode and much more. It’s extremely easy to work with as you just need a couple of lines of XAML. The only shortcoming is that at the time of writing it seems that there is no way to read the current zoom state, making it difficult to fully support tombstoning. If you don’t need this, go grab Multitouch Behavior and stop reading: it will probably work better and you’ll save some time.</p>
<h2>The XAML</h2>
<p>This is the XAML we are starting with. Notice that our DIY implementation relies on the <a href="http://silverlight.codeplex.com/">Silverlight Toolkit’s</a> InputGesture. If you are not yet using it, please install the toolkit and add a reference to Microsoft.Phone.Controls.Toolkit in your project.</p>
<pre class="brush: xml">
xmlns:toolkit=&quot;clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit&quot;
</pre>
<pre class="brush: xml">
&lt;Image x:Name=&quot;ImgZoom&quot;
        Source=&quot;sample.jpg&quot;
        Stretch=&quot;UniformToFill&quot;
        RenderTransformOrigin=&quot;0.5,0.5&quot;&gt;
    &lt;toolkit:GestureService.GestureListener&gt;
        &lt;toolkit:GestureListener
                PinchStarted=&quot;OnPinchStarted&quot;
                PinchDelta=&quot;OnPinchDelta&quot;/&gt;
    &lt;/toolkit:GestureService.GestureListener&gt;
    &lt;Image.RenderTransform&gt;
        &lt;CompositeTransform
                ScaleX=&quot;1&quot; ScaleY=&quot;1&quot;
                TranslateX=&quot;0&quot; TranslateY=&quot;0&quot;/&gt;
    &lt;/Image.RenderTransform&gt;
&lt;/Image&gt;
</pre>
<h2>The wrong way</h2>
<p>I’ve seen this example several times around, I suppose you’ve seen it too somewhere on The Interwebs™:</p>
<pre class="brush: c-sharp">
double initialScale = 1d;

private void OnPinchStarted(object s, PinchStartedGestureEventArgs e)
{
    initialScale = ((CompositeTransform)ImgZoom.RenderTransform).ScaleX;
}

private void OnPinchDelta(object s, PinchGestureEventArgs e)
{
    var transform = (CompositeTransform)ImgZoom.RenderTransform;
    transform.ScaleX = initialScale * e.DistanceRatio;
    transform.ScaleY = transform.ScaleX;
}
</pre>
<p>Very simple and good looking. I love simple solutions and I bet you do too, but as someone once said “Things should be as simple as possible, but not simpler.” And unfortunately this is simpler than possible (is this even a sentence?). The problem is that the scaling is always centered in the middle of the image, so this solution won’t pass the poke-two-fingers-in-the-eyes test.</p>
<h2>The better but still wrong way</h2>
<p>The knee-jerk reaction is to move the scaling center between our fingers as we perform the scaling:</p>
<pre class="brush: c-sharp">
double initialScale = 1d;

private void OnPinchStarted(object s, PinchStartedGestureEventArgs e)
{
    initialScale = ((CompositeTransform)ImgZoom.RenderTransform).ScaleX;
}

private void OnPinchDelta(object s, PinchGestureEventArgs e)
{
    var finger1 = e.GetPosition(ImgZoom, 0);
    var finger2 = e.GetPosition(ImgZoom, 1);

    var center = new Point(
        (finger2.X + finger1.X) / 2 / ImgZoom.ActualWidth,
        (finger2.Y + finger1.Y) / 2 / ImgZoom.ActualHeight);

    ImgZoom.RenderTransformOrigin = center;

    var transform = (CompositeTransform)ImgZoom.RenderTransform;
    transform.ScaleX = initialScale * e.DistanceRatio;
    transform.ScaleY = transform.ScaleX;
}
</pre>
<p>This is better. The first time it actually works well too, but as soon as you pinch the image a second time you realize the image moves around. The reason: the zoom state is <em>the sum of all the zoom operations</em> (each one having its center) and by moving the center every time you are effectively removing information from the previous steps. To solve this problem we could replace the CompositeTransform with a TransformGroup and then add a new ScaleTransform (with a new center) at every PinchStart+PinchDelta event group. This will probably work: every scaling will keep its center and all is well. Except your phone will probably catch fire and explode because of the number of transforms you are stacking up. My team has a name for this kind of solutions, and it isn’t a nice one (fortunately there is no English translation for that).</p>
<h2>The right way</h2>
<p>It is clear by now that simply setting a scale factor and moving the center won’t take us far. As we are real DIYourselfers we will do it with a combination of scaling and translation. In the <a href="http://adtsai.blogspot.com/2010/09/pinch-zooming-using-xna4-on-wp7-getting.html">already mentioned article</a>, Adrian Tsai uses this technique in XNA and we will apply the same concept in Silverlight. If an image is worth a million worth, a line of code is probably worth even more, so I’ll let the c# do the talking.</p>
<pre class="brush: c-sharp">
// these two fully define the zoom state:
private double TotalImageScale = 1d;
private Point ImagePosition = new Point(0, 0);

private Point _oldFinger1;
private Point _oldFinger2;
private double _oldScaleFactor;

private void OnPinchStarted(object s, PinchStartedGestureEventArgs e)
{
    _oldFinger1 = e.GetPosition(ImgZoom, 0);
    _oldFinger2 = e.GetPosition(ImgZoom, 1);
    _oldScaleFactor = 1;
}

private void OnPinchDelta(object s, PinchGestureEventArgs e)
{
    var scaleFactor = e.DistanceRatio / _oldScaleFactor;

    var currentFinger1 = e.GetPosition(ImgZoom, 0);
    var currentFinger2 = e.GetPosition(ImgZoom, 1);

    var translationDelta = GetTranslationDelta(
        currentFinger1,
        currentFinger2,
        _oldFinger1,
        _oldFinger2,
        ImagePosition,
        scaleFactor);

    _oldFinger1 = currentFinger1;
    _oldFinger2 = currentFinger2;
    _oldScaleFactor = e.DistanceRatio;

    UpdateImage(scaleFactor, translationDelta);
}

private void UpdateImage(double scaleFactor, Point delta)
{
    TotalImageScale *= scaleFactor;
    ImagePosition = new Point(ImagePosition.X + delta.X, ImagePosition.Y + delta.Y);

    var transform = (CompositeTransform)ImgZoom.RenderTransform;
    transform.ScaleX = TotalImageScale;
    transform.ScaleY = TotalImageScale;
    transform.TranslateX = ImagePosition.X;
    transform.TranslateY = ImagePosition.Y;
}

private Point GetTranslationDelta(
    Point currentFinger1, Point currentFinger2,
    Point oldFinger1, Point oldFinger2,
    Point currentPosition, double scaleFactor)
{
    var newPos1 = new Point(
        currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
        currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

    var newPos2 = new Point(
        currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
        currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

    var newPos = new Point(
        (newPos1.X + newPos2.X) / 2,
        (newPos1.Y + newPos2.Y) / 2);

    return new Point(
        newPos.X - currentPosition.X,
        newPos.Y - currentPosition.Y);
}
</pre>
<p>Also note that in the XAML we must set the RenderTransformOrigin to 0,0.<br />
This finally passes the fingers-in-the-eyes test! Now we can add some bells and whistles like handling dragging, blocking the zoom-out when the image is at full screen, and avoiding that the image is dragged outside the visible area. For those extra details please see the sample solution at the end of the article.</p>
<h2>What about MVVM?</h2>
<p>You are using MVVM-light for your WP7 app, aren’t you? We all agree my code is ugly and not very MVVM friendly, I&#8217;ll make no excuses. However it’s all strictly UI code, so it doesn’t feel so bad to have it in the code behind. What you will probably do is wire TotalImageScale and ImagePosition to your ViewModel. Those two values fully define the state of the zoom, so if you save and reload them in your ViewModel you will be good to go.</p>
<h2>Download</h2>
<p>Here is <a href="/wp-content/uploads/2011/03/PinchZoom.zip">the full sample project</a> so that you can play with the code within the comfort of your Visual Studio (my daughter is in the picture, please treat her with respect <img src='http://www.frenk.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ).<br />
Feel free to use the code in your project. As always, any kind of feedback is deeply appreciated!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.frenk.com/2011/03/windows-phone-7-correct-pinch-zoom-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
	</channel>
</rss>

