<?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>Stoney's Zone &#187; Languages</title>
	<atom:link href="http://stoney.sb.org/wordpress/category/languages/feed/" rel="self" type="application/rss+xml" />
	<link>http://stoney.sb.org/wordpress</link>
	<description>Thoughts about stuff</description>
	<lastBuildDate>Thu, 24 Dec 2009 16:49:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Defining new format wrappers in Mathematica</title>
		<link>http://stoney.sb.org/wordpress/2009/06/defining-new-format-wrappers-in-mathematica/</link>
		<comments>http://stoney.sb.org/wordpress/2009/06/defining-new-format-wrappers-in-mathematica/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 23:10:05 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=102</guid>
		<description><![CDATA[One problem I had with the expression-to-C converter is that CForm converts negations of terms into a negation of parenthesized terms. For example: In[1]:= -a b // CForm Out[1]//CForm= -(a*b) That looks ugly. I tried to define a new format for Times[-1, v], but this requires unprotecting Times, and led to an infinite recursion when [...]]]></description>
			<content:encoded><![CDATA[<p>One problem I had with the <a href="http://stoney.sb.org/wordpress/2009/06/converting-symbolic-mathematica-expressions-to-c-code/">expression-to-C converter</a> is that CForm converts negations of terms into a negation of parenthesized terms.</p>
<p><span id="more-102"></span>
<p>For example:</p>
<p>In[1]:= <b>-a b // CForm</b></p>
<p>Out[1]//CForm= -(a*b)</p>
<p>That looks ugly. I tried to define a new format for Times[-1, v], but this requires unprotecting Times, and led to an infinite recursion when I tried to use it. I finally found a suggestion on how to define whole new format wrappers on the comp.soft-sys.math.mathematica list, in a message posted by Carl Woll (a Wolfram employee). This is how it works:</p>
<p>This assignment marks CCForm (my new formatter) as a format wrapper.</p>
<p>In[2]:= <b>Format[CCForm[expr_], CCForm] := expr</b></p>
<p>Note that the Out[3] text shows the new formatter name.</p>
<p>In[3]:= <b>2 + 3 // CCForm</b></p>
<p>Out[3]//CCForm= CCForm[5]</p>
<p>It&#8217;s showing the CCForm wrapper, though, which we don&#8217;t want to look at, so we define a top-level format for CCForm that replaces it with its argument.</p>
<p>In[4]:= <b>Format[CCForm[expr_]] := expr</b></p>
<p>Now, the output looks correct.</p>
<p>In[5]:= <b>2 + 3 // CCForm</b></p>
<p>Out[5]//CCForm= 5</p>
<p>The case I&#8217;m trying to fix isn&#8217;t helped by this. We need to make it produce the CForm.</p>
<p>In[6]:= <b>-a b // CCForm</b></p>
<p>Out[6]//CCForm= -a b</p>
<p>In[7]:= <b>Format[CCForm[expr_]] := CForm[expr]</b></p>
<p>In[8]:= <b>-a b // CCForm</b></p>
<p>Out[8]//CCForm= -(a*b)</p>
<p>We don&#8217;t want the result to be evaluated, so we add a HoldForm.</p>
<p>In[9]:= <b>Format[CCForm[expr_]] := HoldForm[CForm[expr]]</b></p>
<p>In[10]:= <b>-a b // CCForm</b></p>
<p>Out[10]//CCForm= -(a*b)</p>
<p>Now it&#8217;s in CForm, but we still have the parenthesis. I don&#8217;t understand just why this works, but making CCForm HoldAll fixes the problem.</p>
<p>In[11]:= <b>SetAttributes[CCForm, HoldAll]</b></p>
<p>In[12]:= <b>-a b // CCForm</b></p>
<p>Out[12]//CCForm= -a * b</p>
<p>This also prevents evaluation of the expression being formatted.</p>
<p>In[13]:= <b>2 + 3 // CCForm</b></p>
<p>Out[13]//CCForm= 2 + 3</p>
<p>Note that CForm does what I want if it&#8217;s made HoldAll.</p>
<p>In[14]:= <b>-a b // CForm</b></p>
<p>Out[14]//CForm= -(a*b)</p>
<p>In[15]:= <b>SetAttributes[CForm, HoldAll]</b></p>
<p>In[16]:= <b>-a b // CForm</b></p>
<p>Out[16]//CForm= -a*b</p>
<p>Although it&#8217;s not styled as nicely as the CCForm version, and could mess up existing code, so we won&#8217;t do that.</p>
<p>In[17]:= <b>ClearAttributes[CForm, HoldAll]</b></p>
<p>Now I can use CCForm instead of CForm for the output formatting of my converter, and have nicer-looking results.</p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2009/06/defining-new-format-wrappers-in-mathematica/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting symbolic Mathematica expressions to C code</title>
		<link>http://stoney.sb.org/wordpress/2009/06/converting-symbolic-mathematica-expressions-to-c-code/</link>
		<comments>http://stoney.sb.org/wordpress/2009/06/converting-symbolic-mathematica-expressions-to-c-code/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 22:49:32 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=99</guid>
		<description><![CDATA[I frequently use Mathematica to rearrange or solve symbolic equations to use in C++ programs. While Mathematica is quite powerful for that, it has no facility to hoist common subexpressions into variables. After spending some time manually rearranging a closed-form solution to a system of equations, it seemed worthwhile to find a way to hoist [...]]]></description>
			<content:encoded><![CDATA[<p>I frequently use <a href="http://www.wolfram.com/products/mathematica/index.html">Mathematica</a> to rearrange or solve symbolic equations to use in C++ programs. While Mathematica is quite powerful for that, it has no facility to hoist common subexpressions into variables.</p>
<p><span id="more-99"></span>
<p>After spending some time manually rearranging a closed-form solution to a system of equations, it seemed worthwhile to find a way to hoist common subexpressions into variables. I didn&#8217;t find anything useful via Google, as the results were swamped by references to the common compiler &#8220;<a href="http://en.wikipedia.org/wiki/Common_subexpression_elimination">common subexpression elimination</a>&#8221; optimization. It looked like it would require <a href="http://en.wikipedia.org/wiki/Dataflow_analysis">data-flow analysis</a> to do this, which would be tedious to write and debug.</p>
<p>Some thought and experimentation suggested that it wouldn&#8217;t be all that hard to do a decent job using a straight-forward pattern matching and replacement (especially since I didn&#8217;t care how fast this ran), so I created this <a href="http://stoney.sb.org/wordpress/wp-content/convertingtocwithcse.zip" title="ConvertingToCwithCSE.zip">Mathematica 7 notebook</a> to do just that. The code turned out to be concise, which means &#8220;unreadable&#8221; in Mathematica. I try to stick to <a href="http://en.wikipedia.org/wiki/Functional_programming">functional style</a> where I can, which is nice mental exercise, but can be hard to read. In the main function, I opted for iteration rather than a purely functional recursion just because it seemed clearer.</p>
<p>It&#8217;s always interesting to work on a problem like this in Mathematica. The language is very expressive, but often fails at the &#8220;<a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment">Principle of Least Surprise</a>&#8220;. In this case, I kept being tripped up by Mathematica matching non-existant arithmetic functions (Plus, Times, etc.) everywhere in an expression, in an overly-helpful attempt to match arithmetic patterns regardless of commutative or associative expression rearrangements. For future reference, it turns out that using HoldPattern will prevent that behavior.</p>
<p>I created a web page from the Mathematica notebook, but there doesn&#8217;t appear to be any way to do that and produce text, rather than pictures of the code. Oh well. <a href="http://stoney.sb.org/wordpress/wp-content/cvt2c/" target="_blank">Here it is</a> anyway. If you want to see this notebook properly and don&#8217;t have Mathematica 7, you can use the free <a href="http://www.wolfram.com/products/player/download.cgi">Mathematica Player</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2009/06/converting-symbolic-mathematica-expressions-to-c-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding a keyboard shortcut to Mathematica V7</title>
		<link>http://stoney.sb.org/wordpress/2008/12/adding-a-keyboard-shortcut-to-mathematica-v7/</link>
		<comments>http://stoney.sb.org/wordpress/2008/12/adding-a-keyboard-shortcut-to-mathematica-v7/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 22:06:38 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=73</guid>
		<description><![CDATA[(updated 2009-03-23 to add the backslashes that disappeared between my blog editor and WordPress) In Mathematica, typing index brackets is clumsy, as one has to type esc-[[-esc then esc-]]-esc. I found a way to modify the Edit menu to add a shortcut for this. I don&#8217;t know how this would be done from non-Macintosh systems, [...]]]></description>
			<content:encoded><![CDATA[<p>(updated 2009-03-23 to add the backslashes that disappeared between my blog editor and WordPress)</p>
<p>In Mathematica, typing index brackets is clumsy, as one has to type esc-[[-esc then esc-]]-esc. I found a way to modify the Edit menu to add a shortcut for this.<span id="more-73"></span><br />
I don&#8217;t know how this would be done from non-Macintosh systems, but on Macintosh, you copy the file &#8220;/Applications/Mathematica.app/SystemFiles/FrontEnd/TextResources/Macintosh/MenuSetup.tr&#8221; (in the Application bundle) into &#8220;~/Library/Mathematica/SystemFiles/FrontEnd/TextResources/Macintosh/MenuSetup.tr&#8221;. Then, edit it using a plain text editor like BBEdit, or even with Mathematica itself.</p>
<p>In this file, find the line</p>

<div class="wp_syntax"><div class="code"><pre class="mathematica" style="font-family:monospace;">MenuItem[&quot;Matching []&quot;, &quot;InsertMatchingBrackets&quot;, MenuKey[&quot;]&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;}]],</pre></div></div>

<p>In the same block of menu items, add this</p>

<div class="wp_syntax"><div class="code"><pre class="mathematica" style="font-family:monospace;">MenuItem[&quot;Matching [LeftDoubleBracket][RightDoubleBracket]&quot;,
    FrontEndExecute[{
        FrontEnd`NotebookApply[FrontEnd`InputNotebook[],
            &quot;[LeftDoubleBracket][SelectionPlaceholder][RightDoubleBracket]&quot;]}],
    MenuKey[&quot;]&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;, &quot;Control&quot;}]],</pre></div></div>

<p>You have to restart Mathematica for it to see this change, but now you can wrap index brackets around the selection by typing cmd-opt-ctl-].</p>
<p>This is different from the other &#8220;Matching&#8230;&#8221; insertions, as it wraps the brackets around the selection, or leaves a &#8220;placeholder&#8221; selected if there was no selection rather than replacing the selection with the insertion. Since I&#8217;m used to editors that wrap the selection in this case, I&#8217;ve also changed the existing &#8220;Matching&#8230;&#8221; menu items to use this same technique.</p>
<p>This is what I have now:</p>

<div class="wp_syntax"><div class="code"><pre class="mathematica" style="font-family:monospace;">MenuItem[&quot;Matching []&quot;,
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],&quot;[[SelectionPlaceholder]]&quot;]}],
    MenuKey[&quot;]&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;}]],
MenuItem[&quot;Matching {}&quot;,
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],&quot;{[SelectionPlaceholder]}&quot;]}],
    MenuKey[&quot;}&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;}]],
MenuItem[&quot;Matching ()&quot;,
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],&quot;([SelectionPlaceholder])&quot;]}],
    MenuKey[&quot;)&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;}]],
MenuItem[&quot;Matching [LeftDoubleBracket][RightDoubleBracket]&quot;,
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],&quot;[LeftDoubleBracket][SelectionPlaceholder][RightDoubleBracket]&quot;]}],
    MenuKey[&quot;]&quot;, Modifiers-&gt;{&quot;Command&quot;, &quot;Option&quot;, &quot;Control&quot;}]],</pre></div></div>

<p>These changes should survive minor updates to Mathematica, but it&#8217;s best to keep a copy of your file in case some later update replaces it.</p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2008/12/adding-a-keyboard-shortcut-to-mathematica-v7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pixel-perfect Graphics, Revisited</title>
		<link>http://stoney.sb.org/wordpress/2008/11/pixel-perfect-graphics-revisited/</link>
		<comments>http://stoney.sb.org/wordpress/2008/11/pixel-perfect-graphics-revisited/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 23:43:21 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=60</guid>
		<description><![CDATA[Mathematica 7 introduces a new Image function that eliminates all the hassle previously necessary to create and export pixel-perfect raster images. Instead of using ArrayPlot to generate the image, I can now do this: myImage = Image[imageData, ColorSpace->RGBColor] I still need to specify RGBColor to interpret the alpha channel correctly, but the option to Image [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.wolfram.com/products/mathematica/index.html">Mathematica 7</a> introduces a new <a href="http://reference.wolfram.com/mathematica/ref/Image.html?q=Image&#038;lang=en">Image</a> function that eliminates all the hassle <a href="http://stoney.sb.org/wordpress/?p=50">previously necessary</a> to create and export pixel-perfect raster images.</p>
<p><span id="more-60"></span></p>
<p>Instead of using <a href="http://reference.wolfram.com/mathematica/ref/ArrayPlot.html?q=ArrayPlot&#038;lang=en">ArrayPlot</a> to generate the image, I can now do this:</p>
<p>
<pre>
myImage = Image[imageData, ColorSpace->RGBColor]
</pre>
<p><img src="http://stoney.sb.org/wordpress/wp-content/myimage.png" alt="myImage.png" border="0" width="256" height="128" />
</p>
<p>I still need to specify <a href="http://reference.wolfram.com/mathematica/ref/RGBColor.html">RGBColor</a> to interpret the alpha channel correctly, but the option to Image is named <a href="http://reference.wolfram.com/mathematica/ref/ColorSpace.html?q=ColorSpace&#038;lang=en">ColorSpace</a>, instead of the <a href="">ColorFunction</a> used by ArrayPlot.</p>
<p>Exporting works the same way as before:</p>
<pre>
Export["~/Desktop/myImage.png", myImage]
</pre>
</p>
<p>Except that now I can directly export a png with alpha. Much simpler overall in the new Mathematica.</p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2008/11/pixel-perfect-graphics-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exporting Pixel-Perfect Graphics in Mathematica</title>
		<link>http://stoney.sb.org/wordpress/2008/09/exporting-pixel-perfect-graphics-in-mathematica/</link>
		<comments>http://stoney.sb.org/wordpress/2008/09/exporting-pixel-perfect-graphics-in-mathematica/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 19:46:06 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=50</guid>
		<description><![CDATA[I keep having to figure out how to export pixel-perfect raster images from Mathematica, which I use for test images with my software. I found that it&#8217;s simpler to use ArrayPlot than Raster now, so I&#8217;m documenting this for my future use (and any one else&#8217;s). Here&#8217;s a simple image function that generates a grid [...]]]></description>
			<content:encoded><![CDATA[<p>I keep having to figure out how to export pixel-perfect raster images from Mathematica, which I use for test images with my software. I found that it&#8217;s simpler to use ArrayPlot than Raster now, so I&#8217;m documenting this for my future use (and any one else&#8217;s).<br />
<span id="more-50"></span>Here&#8217;s a simple image function that generates a grid of black pixels alternating with nearly-transparent red pixels. I use this sort of image to ensure that I&#8217;m sampling correctly.</p>
<pre>
imageFunction[x_, y_] :=
 If[BitAnd[x, 1] == BitAnd[y, 1],
  {0, 0, 0, 1},
  {1, 0, 0, 0.01}]
</pre>
<p>Table then makes a 256 x 128 array of RGBA values from the image function. This is non-square for this example to ensure that the width and height are in the right order later.</p>
<pre>
imageData = Table[
   imageFunction[x, y],
   {y, 0, 127}, {x, 0, 255}];
</pre>
<p>ArrayPlot makes the pixel array viewable by converting it into a Graphics. The ColorFunction produces RGBA pixels (the default ignores alpha), PixelConstrained aligns the image to exact pixel boundaries, and ImageSize produces a result that&#8217;s exactly the right size.</p>
<pre>
apic = ArrayPlot[
  imageData,
  ColorFunction -> RGBColor,
  PixelConstrained -> True,
  ImageSize -> Reverse[Take[Dimensions[imageData], 2]]]
</pre>
<p>This produces the image:</p>
<p>
<img src="http://stoney.sb.org/wordpress/wp-content/apic.png" alt="APic.png" border="0" width="256" height="128" />
</p>
<p>Which is then exported like this:</p>
<pre>
Export["~/Desktop/APic.tif", apic];
</pre>
<p>The result is a pixel-perfect file resulting from a raster image defined in Mathematica.</p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2008/09/exporting-pixel-perfect-graphics-in-mathematica/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Your Father&#8217;s Parentheses</title>
		<link>http://stoney.sb.org/wordpress/2007/08/your-fathers-parentheses/</link>
		<comments>http://stoney.sb.org/wordpress/2007/08/your-fathers-parentheses/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 15:37:21 +0000</pubDate>
		<dc:creator>stoney</dc:creator>
				<category><![CDATA[Humor]]></category>
		<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://stoney.sb.org/wordpress/?p=38</guid>
		<description><![CDATA[From XKCD]]></description>
			<content:encoded><![CDATA[<p>From <a href="http://xkcd.com/" target="_blank" title="XKCD">XKCD</a></p>
<p><a href="http://xkcd.com/297/"><img src="http://imgs.xkcd.com/comics/lisp_cycles.png" height="141" width="426" border="1" hspace="4" vspace="4" alt="Lisp Cycles" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://stoney.sb.org/wordpress/2007/08/your-fathers-parentheses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
