<?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>Cerebral Mastication &#187; technical</title>
	<atom:link href="http://www.cerebralmastication.com/tag/technical/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cerebralmastication.com</link>
	<description>Something to Chew On</description>
	<lastBuildDate>Fri, 16 Jul 2010 22:07:12 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Anna Karenina Yield Anomaly</title>
		<link>http://www.cerebralmastication.com/2009/03/the-anna-karenina-yield-anomaly/</link>
		<comments>http://www.cerebralmastication.com/2009/03/the-anna-karenina-yield-anomaly/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 18:30:18 +0000</pubDate>
		<dc:creator>JD Long</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[agriculture]]></category>
		<category><![CDATA[econ]]></category>
		<category><![CDATA[technical]]></category>

		<guid isPermaLink="false">http://www.cerebralmastication.com/?p=239</guid>
		<description><![CDATA[Leo Tolstoy begins  Anna Karenina with the famous lines: &#8220;All happy families are happy  in the same way. All miserable families are miserable in their own  way.&#8221;
I did my graduate thesis on the spatial relationship of stochastic variables. The stochastic variable which I found most interesting at the time was farmer corn [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_240" class="wp-caption alignleft" style="width: 167px"><a href="http://en.wikipedia.org/wiki/Leo_Tolstoy" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Leo_Tolstoy?referer=');"><img class="size-full wp-image-240" title="200px-lntolstoy_prokudin-gorsky" src="http://www.cerebralmastication.com/wp-content/uploads/2009/03/200px-lntolstoy_prokudin-gorsky.jpg" alt="Leo Tolstoy" width="157" height="197" /></a><p class="wp-caption-text">Leo Tolstoy</p></div>
<p>Leo Tolstoy begins  Anna Karenina with the famous lines: &#8220;All happy families are happy  in the same way. All miserable families are miserable in their own  way.&#8221;</p>
<p>I did my graduate thesis on the spatial relationship of stochastic variables. The stochastic variable which I found most interesting at the time was farmer corn yields. Since yields can&#8217;t go any lower than zero I had a preconceived notion that in bad years all farmer yields were bunched up down close to zero and on good years yields were very spread out with some farmers having average yields and some having nearly double their average yields.  I was pretty surprised when I found that good year yield distributions look like this:</p>
<div id="attachment_243" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-243" title="il_2006" src="http://www.cerebralmastication.com/wp-content/uploads/2009/03/il_2006-300x300.png" alt="IL Corn 2006" width="300" height="300" /><p class="wp-caption-text">IL Corn 2006</p></div>
<p>and bad years look like this:</p>
<div id="attachment_244" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-244" title="il_2002" src="http://www.cerebralmastication.com/wp-content/uploads/2009/03/il_2002-300x300.png" alt="IL Corn 2002" width="300" height="300" /><p class="wp-caption-text">IL Corn 2002</p></div>
<p>I was surprised by the notion that when yields are relatively low, like in 2002, the distribution has so much more dispersion. And in &#8220;good&#8221; years, like 2006, the distribution is rather compact. This pattern holds across other crops, other states, and different levels of aggregation/disaggregation.</p>
<p>So in happy years all farmers are happy together, but in miserable years each one in miserable in their own special way.</p>
<p>There are interesting spatial correlation impacts of this which are quite intuitive. If a good year is defined as &#8216;everyone does well&#8217; then the spatial correlation is quite high since everyone is doing well. But bad years are defined by some doing ok, and some doing quite bad. This results in much lower spatial correlation.</p>
<p>Sooooo&#8230; BOTH the distribution shape AND the correlation matrix of crop yields must vary with yield level. That makes a proper stochastic model a bit tricky, no? Typically we assume the correlation matrix to be fixed and not a variable. That&#8217;s why it&#8217;s never boring to be a stochastic agricultural economist.</p>
<p>Footnote: The above graphs are PDFs based on county yields, not producer yields, but yields are fractal so the producer level yield distributions have a very similar shape.  Data is from the National Agricultural Statistical Service (NASS).  PDFs were done in R using the density function.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cerebralmastication.com/2009/03/the-anna-karenina-yield-anomaly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mandelbrot Set in R</title>
		<link>http://www.cerebralmastication.com/2009/02/mandelbrot-set-in-r/</link>
		<comments>http://www.cerebralmastication.com/2009/02/mandelbrot-set-in-r/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 14:53:50 +0000</pubDate>
		<dc:creator>JD Long</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[fractal]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[technical]]></category>

		<guid isPermaLink="false">http://www.cerebralmastication.com/?p=33</guid>
		<description><![CDATA[After writing the previous entry about Taleb and Mandelbrot I was thinking, &#8220;hey, I should be able to create the Mandelbrot set using R.&#8221; I&#8217;ve never actually tried to code the Mandelbrot set, but it seems easy enough. Well I messed with it for 2 maybe 3 seconds and then Googled [Mandelbrot set r] and, [...]]]></description>
			<content:encoded><![CDATA[<p>After writing the previous entry about <a href="http://www.cerebralmastication.com/?p=19">Taleb and Mandelbrot </a>I was thinking, &#8220;hey, I should be able to create the Mandelbrot set using R.&#8221; I&#8217;ve never actually tried to code the Mandelbrot set, but it seems easy enough. Well I messed with it for 2 maybe 3 seconds and then Googled [Mandelbrot set r] and, no surprise, I found a great implementation that not only produces the Mandelbrot set, it produces it with animation!  As we all know, animation makes it betterer.</p>
<p style="text-align: center;">
<p style="text-align: center;"><img class="size-full wp-image-40 aligncenter" title="mandelbrot1" src="http://www.cerebralmastication.com/wp-content/uploads/2009/02/mandelbrot1.gif" alt="mandelbrot1" width="400" height="400" /></p>
<p>Pretty cool, ey? Well special credit goes to Jarek Tuszynski, PhD. over at Science Applications International Corporation who cobbled this together and posted it on a <a href="http://tolstoy.newcastle.edu.au/R/help/05/10/13198.html" onclick="pageTracker._trackPageview('/outgoing/tolstoy.newcastle.edu.au/R/help/05/10/13198.html?referer=');">CRAN email list</a>.</p>
<p>All the gory details (and source code!) after the break!<span id="more-33"></span></p>
<p>Here&#8217;s the R code Jarek wrote:</p>
<blockquote><p>library(fields)  # for tim.colors<br />
library(caTools) # for write.gif<br />
m = 400          # grid size<br />
C = complex( real=rep(seq(-1.8,0.6, length.out=m), each=m ), imag=rep(seq(-1.2,1.2, length.out=m),      m ) )<br />
C = matrix(C,m,m)</p>
<p>Z = 0<br />
X = array(0, c(m,m,20))<br />
for (k in 1:20) {<br />
Z = Z^2+C<br />
X[,,k] = exp(-abs(Z))<br />
}</p>
<p>image(X[,,k], col=tim.colors(256)) # show final image in R<br />
write.gif(X, &#8220;Mandelbrot.gif&#8221;, col=tim.colors(256), delay=100)</p></blockquote>
<p>Yeah, that&#8217;s it. It runs in 7.2 seconds on my laptop. It took me longer to find the gif on my harddrive than it did to run the code.</p>
<p>How&#8217;s it work, you ask? Freaking R magic, baby!</p>
<p>Oh, you want a real answer? Well, the logic works something like this:</p>
<p>Load up a couple of libraries solely for the creation of the animated gif and the colors:</p>
<blockquote><p>library(fields)<br />
library(caTools)</p></blockquote>
<p>Dr. T&#8217;ski likes to use the equal sign for assignment of variables. While I am sure he is a total R stud, this behavior is very &#8216;un-R.&#8217; In my totally arrogant opinion he should be using the more common R syntax of &#8216;&lt;-&#8217; for assignment. So I would write the next bit like this:</p>
<blockquote><p>m &lt;- 400</p></blockquote>
<p>to assign a value of 400 to the variable m</p>
<p>The next step he nests a bunch of stuff together and assigns that to the variable C. I&#8217;m going to break it up for explanation:</p>
<blockquote><p>seq(-1.8,0.6, length.out=m)</p></blockquote>
<p>This creates a sequence of length 400 (since m=400) that ranges from -1.8 to 0.6. So that sequence looks a lot like this:</p>
<p>-1.800000000 -1.793984962 -1.787969925 &#8230; 0.587969925  0.593984962  0.600000000</p>
<p>except the &#8216;&#8230;&#8217; is replaced by 394 values following that sequence.</p>
<p>The next bit sets the real property equal to a repeating pattern. (In this case he has to use the equal sign because he is not assigning a value to an object called[real], he is setting the real property of the [complex] function. Trust me. I used to be a Boy Scout)</p>
<blockquote><p>real=rep(seq(-1.8,0.6, length.out=m), each=m )</p></blockquote>
<p>This repeats each element of the previous sequence 400 times. So now the parameter [real] is set to a vector of length 160,000 that is the prior sequence, where each element is repeated 400 times. So that helps us understand the next part:</p>
<blockquote><p>imag=rep(seq(-1.2,1.2, length.out=m), m )</p></blockquote>
<p>This is the sequence -1.2 to 1.2 in 400 steps where each step is repeated 400 times. It&#8217;s not the same as the previous step, but it rhymes. Now let&#8217;s bring that all together and define C:</p>
<blockquote><p>C = complex( real=rep(seq(-1.8,0.6, length.out=m), each=m ), imag=rep(seq(-1.2,1.2, length.out=m), m ) )</p></blockquote>
<p>since we already defined [real] and [imag] in the previous steps, let&#8217;s define C like this:</p>
<blockquote><p>real&lt;-rep(seq(-1.8,0.6, length.out=m), each=m )<br />
imag&lt;-rep(seq(-1.2,1.2, length.out=m), m )<br />
C &lt;- complex( real=real, imag=imag )</p></blockquote>
<p>so C is created using the [complex] function on [real] and [imag] vectors. The [complex] function is looking for two parameters, real, and imag. Since we created two vectors by the same name, we used those. So if you try to run C &lt;- complex( real, imag ) you get an error bitching at you about an invalid length.</p>
<p>So what, exactly, is C? It&#8217;s a complex vector made from the vectors [real] and [imag]. Not helpful? Well its a vector where each element has a real component and an imaginary component. So element number 1 of C (i.e. C[1]) is equal to &#8220;-1.8-1.2i&#8221;. Keep in mind that real[1]=-1.8 and imag[1]=-1.2. So C is a vector of length 160,000 where each element has a real component that comes from [real] and an imaginary component from [imag]. Head on over to Wikipedia if you need a <a href="http://en.wikipedia.org/wiki/Complex_number" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Complex_number?referer=');">refresher on complex numbers</a>.</p>
<p>At this point you should be reminded of the following XKCD comic:</p>
<p><a href="http://xkcd.com/179/" onclick="pageTracker._trackPageview('/outgoing/xkcd.com/179/?referer=');"><img class="alignnone" src="http://imgs.xkcd.com/comics/e_to_the_pi_times_i.png" alt="" width="278" height="333" /></a></p>
<p>So now that we have that straight, what about the next bits? Well to good doctor T&#8217;ski now recycles the variable C to create a matrix using this syntax:</p>
<blockquote><p>C = matrix(C,m,m)</p></blockquote>
<p>So [C] is now a matrix object of size 400 by 400.  The [matrix] function just wraps the long vector C around so that the first 400 elements are the first row, the next 400 elements are the second row, etc. So now instead of C being a vector with 160,000 elements, it is a 400 by 400 matrix with 160,000 elements.</p>
<p>Now that we have C, let&#8217;s move on:</p>
<blockquote><p>Z = 0<br />
X = array(0, c(m,m,20))</p></blockquote>
<p>These two commands set up some objects that will bet populated later. [Z] is assigned a value of 0 and then X is created. X is a multidimensional array of size 400 by 400 by 20. So you can think of X as a 400 by 400 array where each element in that array is a vector of length 20. This is totally tangential, but in R you would access a given element using syntax like X[5,4,20] with the last element in the array being X[400,400,20]. Another way to think about X is to imagine a great big Rubik&#8217;s cube that instead of being 3 by 3 by 3 is of dimensions 400 by 400 by 20. Now picture looking at the 400 by 400 face of that big block. We are about to slice through each of the 20 layers. Oh yeah!</p>
<p>Everything up to this point is really just housekeeping to get ready for this next part that finally looks Mandelbrot-esque:</p>
<blockquote><p>for (k in 1:20) {<br />
Z = Z^2+C<br />
X[,,k] = exp(-abs(Z))<br />
}</p></blockquote>
<p>You&#8217;ll notice that this loop has 20 steps. If you&#8217;ll count the steps in the animated GIF above you will find that it, too, has 20 steps. Conicidence? I think NOT! Remember that 400 by 400 by 20 Rubik&#8217;s cube? (it&#8217;s really a hexahedron, not a cube, but stick with me) Each image in the animated GIF is a 400 by 400 layer from that big array. How does the loop work? I&#8217;m glad you asked!</p>
<p>The complex matrix we created earlier, [C] is going to be repeatedly squared and then have the original [C] added to it. If we refresh ourselves on the Mandelbrot Set we will remember (don&#8217;t you love how I assume we already knew this crap and just forgot it?) that the definition of the Mandelbrot set is a complex quadratic polynomial  <em>z</em><sub><em>n</em>+1</sub> = <em>z</em><sub><em>n</em></sub><sup>2</sup> + <em>c </em>which remains unbounded. Well the loop above iterates through that polynomial.</p>
<p>The first time through this loop Z is 0 so Z^2+C ends up being just C. The next part of the loop takes the absolute value of each element in Z, then makes that negative. So all elements end up negative.  Then the exponential function (exp) is applied to each element.  So if the first two elements of Z had been 2,-3 they would be transformed into 0.135335,0.049787. The exponential function is required to transform the complex number into something that can actually be plotted. Look up at the cartoon above&#8230; see how you can raise e to the power of an imaginary number? Well the <a href="http://en.wikipedia.org/wiki/Exponential_function" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Exponential_function?referer=');">exponential function just raises e </a>to the power of the each complex number in [Z]. Cool, ey?</p>
<p>From what I can tell it seems the &#8216;-abs&#8217; bit is really optional. The image ends up the same if you simple do  X[,,k] = exp(Z).</p>
<p>The whole matrix Z is then inserted as a layer into our 400 by 400 by 20 array. The very first layer (k=1) looks like this:</p>
<p><img class="aligncenter size-full wp-image-42" title="mandelbrot1" src="http://www.cerebralmastication.com/wp-content/uploads/2009/02/mandelbrot1.png" alt="mandelbrot1" width="400" height="400" /></p>
<p>The next time through the loop (k=2) [Z] is much more complex. Instead of being 0, [Z] is now the initial matrix [C]. So on the second loop we square each element of  [Z], add the elements of [C]  to the squared values of [Z] then take the absolute value of each element, make each element negative, raise e to the power of each element (exponential function) and POOF we just created another layer of the image! We do that process 20 times.</p>
<p>The &#8216;real&#8217; Mandelbrot set does not stop at 20 but rather continues for infinity. But the really neat thing about the Mandelbrot set is that as you iterate through the steps, the shape does not change&#8230; it just repeats the same pattern over and over and over at smaller intervals. It&#8217;s like zooming in to a beach from space. At first you see a rough shore line, then a rough rock, then bumps on that rock, then the roughness of the molecules that make up that rock. It just repeats as you zoom in. That&#8217;s fractals, Baby!</p>
<p>Author Clark hosted a great documentary on fractals titled &#8220;The Colors of Infinity.&#8221; Thanks to the interwebs you can <a href="http://www.youtube.com/results?search_type=&amp;search_query=Arthur+Clarke+-+Fractals+-+The+Colors+Of+Infinity" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.youtube.com/results?search_type=_amp_search_query=Arthur+Clarke+-+Fractals+-+The+Colors+Of+Infinity&amp;referer=');">watch the whole thing on YouTube</a>!</p>
<p>Stay tuned, next week I&#8217;ll groom <a href="http://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Schr_C3_B6dinger_27s_cat?referer=');">Schrodinger&#8217;s cat</a>.</p>
<p><em><br />
</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cerebralmastication.com/2009/02/mandelbrot-set-in-r/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
