<?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>Ed&#039;s Big Plans &#187; Eddie Ma</title>
	<atom:link href="http://eddiema.ca/author/edoules/feed/" rel="self" type="application/rss+xml" />
	<link>http://eddiema.ca</link>
	<description>Biology, Computing, Adventure</description>
	<lastBuildDate>Tue, 07 Sep 2010 00:09:27 +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>C# &amp; Bioinformatics: Indexers &amp; Substitution Matrices</title>
		<link>http://eddiema.ca/2010/09/01/c-bioinformatics-indexers-substitution-matrices/</link>
		<comments>http://eddiema.ca/2010/09/01/c-bioinformatics-indexers-substitution-matrices/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 15:15:41 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Computational Biology]]></category>
		<category><![CDATA[Accessors]]></category>
		<category><![CDATA[Brackets]]></category>
		<category><![CDATA[C Sharp]]></category>
		<category><![CDATA[Getters]]></category>
		<category><![CDATA[Indexers]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Substitution Matrices]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1970</guid>
		<description><![CDATA[I&#8217;ve recently come to appreciate the convenience of C# indexers. What indexers allow you to do is to subscript an object using the familiar bracket notation. I&#8217;ve used them for substitution matrices as part of my phylogeny project. Indexers are essentially syntactical sugar that obey the rules of method overloading. I first describe what I think [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently come to appreciate the convenience of C# indexers. What  indexers allow you to do is to subscript an object using the familiar bracket notation. I&#8217;ve used them for substitution matrices as part of my phylogeny project. Indexers are essentially syntactical sugar that obey the rules  of method overloading. I first describe what I think are useful substitution matrix indexers and then a bare bones substitution matrix class (you could use your own). The indexer notation implementation is discussed last, so feel free to skip the preamble if you&#8217;re able to deduce what I&#8217;m doing.</p>
<p><em>Note: <span style="text-decoration: underline;">I&#8217;ve only discussed accessors (getters) and not mutators (setters) today.</span></em></p>
<p><strong>Some Reasonable Substitution Matrix Indexers</strong></p>
<p>This is the notation you might expect from the indexer notation in C#.</p>
<pre class="brush: csharp;">
// Let there be a class called SubMatrix which contains data from BLOSUM62.

var  sm = new SubMatrix( ... );
     // I'll assume you already have some constructors.

int  index_of_proline = sm['P'];
     // Returns the row or column that corresponds to proline, 14.

char token_at_three = sm[3];
     // Returns the amino acid at position three, aspartate.

int  score_proline_to_aspartate = sm['P', 'D'];
     // Returns the score for a mutation from proline to aspartate, -1.

int  score_aspartate_to_proline = sm[3, 14];
     // Returns the score for a mutation from aspartate to proline, -1.
</pre>
<p><strong>An Example Bare Bones Substitution Matrix Class</strong></p>
<p>Let&#8217;s say you&#8217;ve loaded up the BLOSUM62 and are representing it internally in some 2D array&#8230;</p>
<pre class="brush: csharp;">
// We've keying the rows and columns in the order given by BLOSUM62:
// ARNDCQEGHILKMFPSTWYVBZX* (24 rows, columns)

int[,] imatrix;
</pre>
<p>For convenience, let&#8217;s say you&#8217;ll also keep a dictionary to map at which array position one finds each amino acid&#8230;</p>
<pre class="brush: csharp;">
// Keys = amino acid letters, Values = row or column index

Dictionary&lt;char, int&gt; indexOfAA;
</pre>
<p>Finally, we&#8217;ll put these two elements into a class and assume that you&#8217;ve already written your own constructors that will take care of the above two items &#8212; either from accepting arrays and strings as arguments or by reading from raw files. If this isn&#8217;t true and you need more help, feel free to leave a comment and I&#8217;ll extend this bare bones example.</p>
<pre class="brush: csharp;">
// Bare bones class ...
public partial class SubMatrix {

    // Properties ...
    private int[,] imatrix;
    private Dictionary&lt;char, int&gt; indexOfAA;

    // Automatic Properties ...
    public int Width { // Returns number of rows of the matrix.
        get {
            return imatrix.GetLength(0);
        }
    }

    // Constructors ...
    ...
}
</pre>
<p>I&#8217;ve added the automatic property &#8220;Width&#8221; above &#8212; automatic properties are C# members that provide encapsulation: a public face to some arbitrary backend data &#8212; you&#8217;ve been using these all along when you&#8217;ve called &#8220;<span style="font-family: andale mono,times;">List.Count&#8221;</span> or &#8220;<span style="font-family: andale mono,times;">Array.Length</span>&#8220;.</p>
<p><strong>Substitution Matrix Indexer Implementation</strong></p>
<p>You can implement the example substitution matrix indexers as follows. Notice the use of the &#8220;this&#8221; keyword and square[] brackets[] to specify[] arguments[].</p>
<pre class="brush: csharp;">
//And finally ...
public partial class SubMatrix {

    // Indexers ...
    // Give me the row or column index where I can find the token &quot;aa&quot;.
    public int this[char aa] {
        get {
            return this.indexOfAA[aa];
        }
    }
    // Give me the amino acid at the row or column index &quot;index&quot;.
    public char this[int index] {
        get {
            return this.key[index];
        }
    }
    // Give me the score for mutating token &quot;row&quot; to token &quot;column&quot;.
    public double this[char row, char column] {
        get {
            return this.imatrix[this.indexOfAA[row], this.indexOfAA[column]];
        }
    }
    // Give me the score for mutating token at index &quot;row&quot; to index &quot;column&quot;.
    public double this[int row, int column] {
        get {
            return this.imatrix[row, column];
        }
    }
}
</pre>
<p>Similar constructs are available in Python and Ruby but not Java. I&#8217;ll likely cover those later as well as how to set values too.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1970" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/09/01/c-bioinformatics-indexers-substitution-matrices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Edit number of rows shown for ‘Visitor Maps and Who’s Online’</title>
		<link>http://eddiema.ca/2010/08/31/edit-number-of-rows-shown-for-visitor-maps-and-whos-online/</link>
		<comments>http://eddiema.ca/2010/08/31/edit-number-of-rows-shown-for-visitor-maps-and-whos-online/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 14:14:59 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Website Management]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Visitor Maps]]></category>
		<category><![CDATA[Who's Online]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=2193</guid>
		<description><![CDATA[Brief: For those of you who use WordPress, a handy plug-in to see who&#8217;s been viewing your site is Visitor Maps and Who&#8217;s Online. You&#8217;ll notice that there isn&#8217;t a way to change the number of entries (rows) displayed in the Who&#8217;s Online and the Who&#8217;s Been Online pages in the plugin managing pages. In [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Brief: </strong></em>For those of you who use WordPress, a handy plug-in to see who&#8217;s been viewing your site is <a href="http://wordpress.org/extend/plugins/visitor-maps/">Visitor Maps and Who&#8217;s Online</a>. You&#8217;ll notice that there isn&#8217;t a way to change the number of entries (rows) displayed in the <em>Who&#8217;s Online</em> and the <em>Who&#8217;s Been Online</em> pages in the plugin managing pages. In order to change that, you&#8217;re going to dive a little deeper. Here are step by step instructions on how to increase the number of displayed visitors for version 1.5.2..</p>
<p><em><strong>Requirements: </strong></em>Must have &#8220;WordPress&#8221; 3.x installed with the &#8220;Visitor Maps and Who&#8217;s Online&#8221; 1.x plugin installed.</p>
<p>(1) Log into your dashboard (<span style="text-decoration: underline;">wp-admin</span>).<br />
(2) Click on the <span style="text-decoration: underline;">Plugins</span> administration page &#8212; it&#8217;s in the far left column.<br />
(3) Scroll down the page and look for <span style="text-decoration: underline;">Visitor Maps and Who&#8217;s Online</span>.<br />
(4) Click on <span style="text-decoration: underline;">Edit</span> (near Deactivate and Settings).<br />
(5) In the far right column named <span style="text-decoration: underline;">Plugin Files</span>, click on &#8220;<span style="font-family: andale mono,times;">visitor-maps/class-wo-been.php</span>&#8220;.</p>
<p><img style="border:1px black solid" class="size-full wp-image-2205 alignnone" title="ClickOnWoBeen" src="http://eddiema.ca/wp-content/uploads/2010/08/ClickOnWoBeen.png" alt="" width="212" height="271" /></p>
<p>(6) In the text area named &#8220;<span style="text-decoration: underline;">Editing visitor-maps/class-wo-been.php (inactive)</span>&#8221; Search for the string &#8220;<span style="font-family: andale mono,times;">$rows_per_page = 25;</span>&#8220;.</p>
<p><img style="border:1px black solid" class="size-full wp-image-2203 alignnone" title="RowsPerPage" src="http://eddiema.ca/wp-content/uploads/2010/08/RowsPerPage.png" alt="" width="448" height="198" /></p>
<p>(7) Change the integer &#8220;<span style="font-family: andale mono,times;">25</span>&#8221; to any whole number you want. I chose &#8220;<span style="font-family: andale mono,times;">100</span>&#8220;.<br />
(8) Click on the button below labelled <span style="text-decoration: underline;">Update File</span>.</p>
<p><img style="border:1px black solid" class="size-full wp-image-2202 alignnone" title="UpdateFile" src="http://eddiema.ca/wp-content/uploads/2010/08/UpdateFile.png" alt="" width="384" height="145" /></p>
<p>And you&#8217;re done! To see the results, click on &#8220;Who&#8217;s Been Online&#8221; and checkout the extended list of visitors per page.</p>
<p><em><strong>Still Unsolved: </strong></em>There&#8217;s still one item I haven&#8217;t really looked into. The display that you get back is not actually the number of rows defined by <span style="font-family: andale mono,times;">$rows_per_page</span> &#8212; instead, this variable only tells the plugin the number of entries to load. What this means is that turning on a filter like &#8220;Show Bots: No&#8221; in &#8220;Who&#8217;s Been Online&#8221; counts the total number of entries <em>with</em> bots included, then removes them from the display &#8212; you end up <span style="font-family: andale mono,times;">$rows_per_page</span> minus the number of bots displayed <em>instead of</em> a total of <span style="font-family: andale mono,times;">$rows_per_page</span> non-bot rows. I&#8217;ll wait till the next version, perhaps the author is already working on it. For now, this quick fix should help.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2193" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/08/31/edit-number-of-rows-shown-for-visitor-maps-and-whos-online/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# &amp; Bioinformatics: Align Strings to Edit Strings</title>
		<link>http://eddiema.ca/2010/08/21/c-bioinformatics-align-strings-to-edit-strings/</link>
		<comments>http://eddiema.ca/2010/08/21/c-bioinformatics-align-strings-to-edit-strings/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 01:03:12 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Computational Biology]]></category>
		<category><![CDATA[Alignment Strings]]></category>
		<category><![CDATA[biosequences]]></category>
		<category><![CDATA[C Sharp]]></category>
		<category><![CDATA[Edit Strings]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1972</guid>
		<description><![CDATA[This post follows roughly from the e-strings (R. Edgar, 2004) topic that I posted about here. The previous source code was listed in Ruby and JS, but this time I&#8217;ve used C#. In this post, I discuss alignment strings (a-strings), then why and how to convert them into edit strings (e-strings). Incidentally, I can&#8217;t seem [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post follows roughly from the e-strings (<a href="http://www.biomedcentral.com/1471-2105/5/113">R. Edgar, 2004</a>) topic that I posted about <a href="http://eddiema.ca/2010/07/24/bioinformatics-edit-strings-ruby-javascript/">here</a>. The previous source code was listed in Ruby and JS, but this time I&#8217;ve used C#.<br />
</em></p>
<p>In this post, I discuss alignment strings (a-strings), then why and how to convert them into edit strings (e-strings). Incidentally, I can&#8217;t seem to recover where I first saw alignment strings so tell me if you know.</p>
<p><strong>Alignment strings</strong></p>
<p>When you perform a pairwise sequence alignment, the transformation that you perform on the two sequences is finite. You can record precisely where insertions, deletions and substitutions (or matches) are made. This is useful if you want to retain the original sequences, or later on build a multiple sequence alignment while keeping the history of modifications. There&#8217;s a datastructure I&#8217;ve seen described called alignment strings, and in it you basically list out the characters &#8216;I&#8217;, &#8216;D&#8217; and &#8216;M&#8217; to describe the pairwise alignment.</p>
<p>Consider the example two protein subsequences below.</p>
<pre>gi|115372949: GQAGDIRRLQSFNFQTYFVRHYN
gi|29827656:  SLSTGVSRSFQSVNYPTRYWQ</pre>
<p>A global alignment of the two using the BLOSUM62 substitution matrix with the gap penalties -12 to open, -1 to extend yields the following.</p>
<pre>gi|115372949: GQAGDIR-----RLQSFNFQTYFVRHYN
gi|29827656:  SL----STGVSRSFQSVNYPT---RYWQ</pre>
<p>The corresponding alignment string looks like this&#8230;</p>
<pre>gi|115372949: GQAGDIR-----RLQSFNFQTYFVRHYN
gi|29827656:  SL----STGVSRSFQSVNYPT---RYWQ
Align String: MMDDDDMIIIIIMMMMMMMMMDDDMMMM</pre>
<p>Remember, the alignment is described such that the top string is modelled as occurring <em>earlier</em> than the bottom string which occurs <em>later</em> &#8212; this is why a gap in the top string is an insertion (that new material is inserted in the later, bottom string) while a gap in the bottom string is a deletion (that material is deleted to make the later string). Notice in reality, it doesn&#8217;t really matter what&#8217;s on top and what&#8217;s on bottom&#8211; the important thing is that the alignment now contains gaps.</p>
<p><strong>Why we should probably use e-strings instead</strong></p>
<p>An alignment string describes the relationship between two strings and their gaps &#8212; we are actually recording some redundant information if we only want to take one string at a time into consideration and the path needed to construct profiles it participates in. The top and bottom sequences are also treated differently, where both &#8216;M&#8217; and &#8216;D&#8217; indicates retention of the original characters for the top string and both &#8216;M&#8217; and &#8216;I&#8217; indicates retention for the bottom string; the remaining character of course implies the inclusion of a gap character. A pair of e-strings would give each of these sequences their own data structure and allow us to cleanly render the sequences as they appear in the deeper nodes of a phylogenetic tree using the <em>multiply</em> operation described <a href="http://eddiema.ca/2010/07/24/bioinformatics-edit-strings-ruby-javascript/">last time</a>.</p>
<p>Here are the corresponding e-strings for the above examples.</p>
<pre>gi|115372949: GQAGDIR-----RLQSFNFQTYFVRHYN
e-string:     &lt; 7, -5, 16 &gt;
gi|29827656:  SL----STGVSRSFQSVNYPT---RYWQ
e-string:     &lt; 2, -4, 16, -3, 4 &gt;</pre>
<p>Recall that an e-string is a list of alternating positive and negative  integers; positive integers mean to retain a substring of the given  length from the originating sequence, and negative integers mean to  place in a gap of the given length.</p>
<p><strong>Converting a-strings to e-strings</strong></p>
<p>Below is a C# code listing for an implementation I used in my project to convert from a-strings to the more versatile e-strings. The thing is &#8212; I really don&#8217;t use a-strings to begin with anymore. In earlier versions of my project, I used to keep track of my movement across the score matrix using an a-string by dumping down a &#8216;D&#8217; for a vertical hop, a &#8216;I&#8217; for a horizontal hop and a &#8216;M&#8217; for a diagonal hop. I now just count the number of relevant steps to generate the matching pair of e-strings.</p>
<p>The function below, <span style="font-family: andale mono,times;">astring_to_estring</span> takes an a-string (<span style="font-family: andale mono,times;">string u</span>) as an argument and returns two e-strings in a list (<span style="font-family: andale mono,times;">List&lt;List&lt;int&gt;&gt;</span>) &#8212; don&#8217;t let that type confuse you, it simply breaks down to a list with two elements in it: the e-string for the top sequence (<span style="font-family: andale mono,times;">List&lt;int&gt; v</span>), and the e-string for the bottom sequence (<span style="font-family: andale mono,times;">List&lt;int&gt; w</span>).</p>
<pre class="brush: csharp;">
public static List&lt;List&lt;int&gt;&gt; astring_to_estring(string u) {
    /* Defined elsewhere are the constant characters ...
       EDITSUB = 'M';
       EDITINS = 'I';
       EDITDEL = 'D';
    */
    var v = new List&lt;int&gt;(); // Top e-string
    var w = new List&lt;int&gt;(); // Bottom e-string
    foreach(var uu in u) {
        if(uu == EDITSUB) { // If we receive a 'M' ...
            if(v.Count == 0) { // Working with e-string v (top, keep)
                v.Add(1);
            } else if(v[v.Count -1] &lt;= 0) {
                v.Add(1);
            } else {
                v[v.Count -1] += 1;
            }
            if(w.Count == 0) { // Working with e-string w (bottom, gap)
                w.Add(1);
            } else if(w[w.Count -1] &lt;= 0) {
                w.Add(1);
            } else {
                w[w.Count -1] += 1;
            }
        } else if(uu == EDITINS) { // If we receive a 'I' ...
            if(v.Count == 0) { // Working with e-string v (top, gap)
                v.Add(-1);
            } else if(v[v.Count -1] &gt;= 0) {
                v.Add(-1);
            } else {
                v[v.Count -1] -= 1;
            }
            if(w.Count == 0) { // Working with e-string w (bottom, keep)
                w.Add(1);
            } else if(w[w.Count -1] &lt;= 0) {
                w.Add(1);
            } else {
                w[w.Count -1] += 1;
            }
        } else if(uu == EDITDEL) { // If we receive a 'D' ...
            if(v.Count == 0) { // Working with e-string v (top, keep)
                v.Add(1);
            } else if(v[v.Count -1] &gt;= 0) {
                v[v.Count -1] += 1;
            } else {
                v.Add(1);
            }
            if(w.Count == 0) { // Working with e-string w (bottom, keep)
                w.Add(-1);
            } else if(w[w.Count -1] &gt;= 0) {
                w.Add(-1);
            } else {
                w[w.Count -1] -= 1;
            }
        }
    }
    var vw = new List&lt;List&lt;int&gt;&gt;(); // Set up return list ...
    vw.Add(v); // Top e-string v added ...
    vw.Add(w); // Bottom e-string w added ...
    return vw;
}
</pre>
<p>The conversion back from e-strings to a-strings is also easy, but I don&#8217;t cover that today. Enjoy and happy coding <img src='http://eddiema.ca/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1972" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/08/21/c-bioinformatics-align-strings-to-edit-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wanted: Semiotics Search Tool</title>
		<link>http://eddiema.ca/2010/08/03/wanted-semiotics-search-tool/</link>
		<comments>http://eddiema.ca/2010/08/03/wanted-semiotics-search-tool/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 17:57:24 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[Search]]></category>
		<category><![CDATA[Semiotics]]></category>
		<category><![CDATA[Sketch]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1587</guid>
		<description><![CDATA[Brief: One of the problems that I&#8217;ve encountered is the complete and utter inability to search for symbols online. One can enter keywords, but there doesn&#8217;t seem to be a good generative grammar or stick-figure search to specify the symbol that you&#8217;ve seen so that you can ask &#8220;what is this figure called&#8221;, &#8220;what does [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Brief:</strong></em> One of the problems that I&#8217;ve encountered is the complete and utter inability to search for symbols online. One can enter keywords, but there doesn&#8217;t seem to be a good generative grammar or stick-figure search to specify the symbol that you&#8217;ve seen so that you can ask &#8220;what is this figure called&#8221;, &#8220;what does this figure mean?&#8221;, &#8220;who does it belong to?&#8221; &#8212; the closest I&#8217;ve found has been this reference, fittingly called <a href="http://www.symbols.com">symbols.com</a> &#8212; but it only offers you a symbol whose name you already know. There are also a few tools that will present several chemical compounds that match a query sketch the user inputs &#8212; here&#8217;s a structure search by <a href="http://pubchem.ncbi.nlm.nih.gov/search/search.cgi">PubChem</a> and another one by <a href="http://www.emolecules.com/">eMolecules</a>.</p>
<p>So what figures do I want to be able to search for? Here are a few example queries &#8230;</p>
<ul>
<li>A circle is drawn with a freehand curve separating the figure roughly into two halves &#8212; should turn up the <a href="http://en.wikipedia.org/wiki/Ying_Yang">Ying Yang</a> along with a few other circular bipartitioned figures.</li>
<li>Two arcs are drawn beside one another concave inward with a staff in the middle &#8212; should turn up the symbol for <a href="http://en.wikipedia.org/wiki/Sikhism">Sikhism</a> and the <a href="http://en.wikipedia.org/wiki/Cadeuceus">Caduceus</a>.</li>
<li>Two to four stick figure humans are placed inside a box &#8212; should turn up the symbol for an elevator or washrooms etc.</li>
</ul>
<p>If anyone knows of a good sketch-based semiotic search tool, please let me  know. Or conversely, if anyone&#8217;s interested in having one developed &#8212;  I&#8217;d be interested in helping <img src='http://eddiema.ca/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1587" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/08/03/wanted-semiotics-search-tool/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Frequent typos of mine</title>
		<link>http://eddiema.ca/2010/07/31/frequent-typos-of-mine/</link>
		<comments>http://eddiema.ca/2010/07/31/frequent-typos-of-mine/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 14:34:54 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Silly]]></category>
		<category><![CDATA[tyops]]></category>
		<category><![CDATA[typos]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1813</guid>
		<description><![CDATA[Brief: There are a few typos that I consistently make. I have concluded that these things have been trained into my brain some how. No matter how much I want to correct them, they just keep showing up. Even conscious efforts to &#8220;not type it wrongly this time&#8221; are only partially successful. It&#8217;s &#8230; like [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Brief: </strong></em>There are a few typos that I consistently make. I have concluded that these things have been trained into my brain some how. No matter how much I want to correct them, they just keep showing up. Even conscious efforts to &#8220;not type it wrongly this time&#8221; are only partially successful. It&#8217;s &#8230; like a speech impediment for my fingers.</p>
<p>Part of me wants to conjecture about motion planning, the cerebellum, buffer overruns and the QWERTY layout &#8212; but a larger part would rather not.</p>
<p>Here&#8217;s a list of words that get these automatic typos &#8212; Yes, <span style="text-decoration: underline;">I know I use four fingers on my left hand</span> plus <span style="text-decoration: underline;">three fingers on my right hand</span> to type &#8212; I think this scheme was inherited from an obsession with the DooM series of first person shooters when I was a primordial computer user.</p>
<ul>
<li>total → <em>tot<strong>oa</strong>l</em> &#8212; redundantly drummed &#8216;o&#8217; with right middle finger.</li>
<li>schematics → <em>schema<strong>it</strong>cs</em> &#8212; incorrect priority given to right middle finger &#8216;i&#8217; over left index &#8216;t&#8217;.</li>
<li>blast → <em>blas<strong>y</strong></em> &#8212; incorrectly increased reaching distance between left middle finger &#8216;s&#8217; to left index &#8216;y&#8217;.</li>
<li>desktop → <em>de<strong>ks</strong>t</em><em>op</em> &#8212; incorrect priority given to right middle finger &#8216;k&#8217; over left index &#8216;s&#8217;.</li>
<li>people → <em>p<strong>oe</strong>ple</em> &#8212; incorrect priority given to right middle finger &#8216;o&#8217; over left middle &#8216;e&#8217;.</li>
</ul>
<p>If you have a patch for my brain, please let me know.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1813" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/07/31/frequent-typos-of-mine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bioinformatics: Edit Strings (Ruby, JavaScript)</title>
		<link>http://eddiema.ca/2010/07/24/bioinformatics-edit-strings-ruby-javascript/</link>
		<comments>http://eddiema.ca/2010/07/24/bioinformatics-edit-strings-ruby-javascript/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 20:34:35 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Computational Biology]]></category>
		<category><![CDATA[Alignment Strings]]></category>
		<category><![CDATA[Edit Strings]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Multiple Sequence Alignment]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1585</guid>
		<description><![CDATA[&#62;&#62;&#62; Attached: ( editStringAdder.rb &#8212; in Ruby &#124; editStrings.js &#8212; in JavaScript ) &#60;&#60;&#60; I wanted to share something neat that I&#8217;ve been using in the phylogeny analyzing software I&#8217;ve been developing. In the MUSCLE3 BMC Bioinformatics paper (Robert Edgar, 2004), Edgar describes a way to describe all the changes required to get from one [...]]]></description>
			<content:encoded><![CDATA[<p>&gt;&gt;&gt; <span style="text-decoration: underline;">Attached</span>: ( <a href="http://eddiema.ca/wp-content/uploads/2010/07/editStringAdder.rb">editStringAdder.rb</a> &#8212; in Ruby | <a href="http://eddiema.ca/wp-content/uploads/2010/07/editStrings.js">editStrings.js</a> &#8212; in JavaScript ) &lt;&lt;&lt;</p>
<p>I wanted to share something neat that I&#8217;ve been using in the phylogeny analyzing software I&#8217;ve been developing. In the <a href="http://www.biomedcentral.com/1471-2105/5/113">MUSCLE3 BMC Bioinformatics paper (Robert Edgar, 2004)</a>, <a href="http://robertedgar.wordpress.com/">Edgar</a> describes a way to describe all the changes required to get from one raw sequence to how it appears somewhere in an internal node, riddled with gaps. He calls the data structures <em>Edit Strings</em> (e-strings).</p>
<p>I started using these things in my visualizer because it is a convenient way to describe how to render a profile of sequences at internal nodes of my phylogenetic trees. Rather than storing a copy of the sequence with gaps at each of its ancestors, e-strings allow you to store a discrete pathway of the changes your alignment algorithm made to a sequence at each node.</p>
<p>You can chain e-strings together with a <em>multiply</em> operation so that the profile of any node in the tree can be created out of just the original primary sequences of the dataset (the taxa) and the set of corresponding e-strings for the given tree. You can choose to store the alphabet-distribution profiles this way at each node too, but I decided to use the e-strings only for my visualizer (where <em>seeing</em> each sequence within a profile is important).</p>
<p>Edit strings take the form of a sequence of alternating positive and negative integers; positive integers mean &#8220;retain a substring of this length&#8221; while negative integers mean &#8220;insert gaps of this length&#8221; &#8212; here&#8217;s a few example applications of edit strings on the sequence &#8220;<span style="font-family: courier new,courier;">ABCDEFGHI</span>&#8220;:</p>
<pre>&lt;10&gt;("ABCDEFGHIJ") = "ABCDEFGHIJ"
&lt;10 -3&gt;("ABCDEFGHIJ") = "ABCDEFGHIJ---"
&lt;4, -2, 6&gt;("ABCDEFGHIJ") = "ABCD--EFGHIJ"
&lt;2, -1, 5, -4, 3&gt;("ABCDEFGHIJ") = "AB-CDEFG----HIJ"</pre>
<p>A few particulars should be mentioned. An application of an e-string onto a sequence is only defined when the sum of the positive integers equals the length of the sequence. The total number of negative integers is arbitrary, and refers to any number of inserted gaps. Finally, a digit zero is meaningless. Edit strings can be <em>multiplied</em> together. If you apply two edit strings in succession onto a sequence, the result is the same as if you had applied the product of two edit strings onto that same sequence. Here are some examples of edit strings multipled together.</p>
<pre>&lt;10&gt; * &lt;10&gt; = &lt;10&gt;
&lt;10&gt; * &lt;7, -1, 2&gt; = &lt;7, -1, 2&gt;
&lt;6, -1, 4&gt; * &lt;7, -1, 3, -2, 1&gt; = &lt;6, -2, 3, -2, 1&gt;
&lt;6, -1, 4&gt; * &lt;3, -1, 3, -1, 3, -1, 2&gt; = &lt;3, -1, 3, -2, 2, -1, 2&gt;
&lt;6, -1, 4&gt; * &lt;2, -1, 6, -5, 3&gt; = &lt;2, -1, 4, -1, 1, -5, 3&gt;</pre>
<p>The multiply function is a bit tricky to implement at first, but one can work backward from the result to get the intermediate step that&#8217;s performed mentally. The last two examples above can manually calculated if we imagine an intermediate step as follows. We convert the first e-string to its application on a sequence of &#8216;+&#8217; symbols&#8211; in both the below cases, this results in ten &#8216;+&#8217; symbols with one &#8216;-&#8217; (gap) inserted after the sixth position. We then apply the second edit string to the result of the first application. Finally, we write out the total changes as an e-string on the original sequence of ten &#8216;+&#8217; symbols. Don&#8217;t worry, we don&#8217;t really do this in real life software &#8212; it&#8217;s just a good way for human brains to comprehend the overall operation.</p>
<p>Second last example above &#8212; expanded out&#8230;</p>
<pre>&lt;6, -1, 4&gt; * &lt;3, -1, 3, -1, 3, -1, 2&gt; = ...
++++++-++++ * &lt;3, -1, 3, -1, 3, -1, 2&gt; = ...
+++-+++--++-++ = &lt;3, -1, 3, -2, 2, -1, 2&gt;</pre>
<p>Last example above &#8212; expanded out&#8230;</p>
<pre>&lt;6, -1, 4&gt; * &lt;2, -1, 6, -5, 3&gt; = ...
++++++-++++ * &lt;2, -1, 6, -5, 3&gt; = ...
++-++++-+-----+++ = &lt;2, -1, 4, -1, 1, -5, 3&gt;</pre>
<p>Here&#8217;s the code in Ruby for my take on the multiply function. I derived my version of the function based on the examples from Edgar&#8217;s BMC paper (mentioned before). When you think about it, the runtime is the sum of the number of elements of the two e-strings being multiplied. This becomes obvious when you realize that the only computation that really occurs is when a positive integer is encountered in the second e-string. The function is called estring_product(), it takes two e-strings as arguments (u, v) and returns a single e-string (w). This function internally calls an estring_collapse() function because we intermediately create an e-string that may have several positive integers or several negative integers in a row (when this happens, it&#8217;s usually just two in a row). Consecutive same-signed integers of an e-string are added together.</p>
<pre class="brush: ruby;">
def estring_product(u, v)
    w = []
    uu_replacement = nil
    ui = 0
    vi = 0
    v.each do |vv|
        if vv &lt; 0
            w &lt;&lt; vv
        elsif vv &gt; 0
            vv_left = vv
            uu = uu_replacement != nil ? uu_replacement : u[ui]
            uu_replacement = nil
            until vv_left == 0
                if vv_left &gt;= uu.abs
                    w &lt;&lt; uu
                    vv_left -= uu.abs
                    ui += 1
                    uu = u[ui]
                else
                    if uu &gt; 0
                        w &lt;&lt; vv_left
                        uu -= vv_left
                    elsif uu &lt; 0
                        w &lt;&lt; -vv_left
                        uu += vv_left
                    end
                    vv_left = 0
                    uu_replacement = uu
                end
            end
        end
        vi += 1
    end
    return estring_collapse(w)
end
</pre>
<p>If you aren&#8217;t familiar with Ruby, the &#8220;&lt;&lt;&#8221; operator means &#8220;append the right value to the left collection&#8221;. Everything else should be pretty self-explanatory (leave a comment if it&#8217;s not).</p>
<pre class="brush: ruby;">
def estring_collapse(u)
    v = []
    u.each do |uu|
        if v[-1] == nil
            v &lt;&lt; uu
        elsif (v[-1] &lt;=&gt; 0) == (uu &lt;=&gt; 0)
            v[-1] += uu
        else
            v &lt;&lt; uu
        end
    end
    return v
end
</pre>
<p>The &#8220;&lt;=&gt;&#8221; lovingly referred to as the spaceship operator compares the right value to the left value; if the right value is greater, then the result is 1.0; if the left value is greater, then the result is -1.0; if the left and right values are the same, then the result is 0.0.</p>
<p><strong>A Few Notes on the Attached Files (Ruby, Javascript)</strong></p>
<p>The Ruby source has a lot of comments in it that should help you understand when and where to use the included two functions. The Javascript is actually used in a visualizer I&#8217;ve deployed now so it has a few more practical functions in it. A function called sequence_estring() is included that takes a $sequence and applies an $estring, then returns a new gapped sequence. A utility signum() function is included which takes the place of the spaceship operator in the Ruby version. A diagnostic function, p_uvw() is included that just uses document.write() to print out whatever you give as (estring) $u, (estring) $v and (estring) $w. Finally, the JavaScript functions sequence_estring() and estring_product() will print out error messages with document.write() when the total sequence length specified in the first argument is not the same as the total sequence length implied by the second argument. Remember, the sum of the <em>absolute values</em> of the first argument describes the total length of the sequence&#8211; each of these tokens must be accounted for by the <em>positive values</em> of the second argument, the estring that will operate on it.</p>
<p><em><strong>Updates to this post:</strong></em></p>
<ol>
<li>Two hyphens in a row were displayed as a single dash &#8212; this has been fixed.</li>
<li>Code listing plug-in uses literal &#8220;&lt;&#8221; and &#8220;&gt;&#8221; instead of the entity codes &#8220;&amp;lt;&#8221; and &#8220;&amp;gt;&#8221; &#8212; fixed.</li>
</ol>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1585" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/07/24/bioinformatics-edit-strings-ruby-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My first TA Evaluations!</title>
		<link>http://eddiema.ca/2010/07/18/my-first-ta-evaluations/</link>
		<comments>http://eddiema.ca/2010/07/18/my-first-ta-evaluations/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 17:19:58 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Academic Life]]></category>
		<category><![CDATA[Ariana Marcassa]]></category>
		<category><![CDATA[BIOL 208]]></category>
		<category><![CDATA[Evaluations]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Teacher Assistant]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1910</guid>
		<description><![CDATA[Brief: I got my TA evaluations from BIOL 208 back last week (which I taught with Ariana in fall 2009) and it looks the students liked my instruction. The overall positive response is encouraging but I&#8217;m concerned that they&#8217;ve actually been too kind. The whole thing was something of a learning experience for me as [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Brief: </strong></em>I got my TA evaluations from BIOL 208 back last week (which I taught with Ariana in fall 2009) and it looks the students liked my instruction. The overall positive response is encouraging but I&#8217;m concerned that they&#8217;ve actually been too kind. The whole thing was something of a learning experience for me as I&#8217;ve never given tutorials before. The written remarks were very informative too. There are two big things the students wanted more of: first, I should increase the depth of my background in the course; second, I should ensure there&#8217;s time to take up quiz and workbook questions. The first item is a bit difficult to do actively mostly because it&#8217;s hard to proactively decide on what kinds of questions a student will have cooked up based on the readings available for a given week. It looks like it&#8217;s a self-repairing problem however &#8212; I simply have to TA more in and around the same topic area until the background information is second hand (or at least until all the keywords are loaded into my brain along with hints toward appropriate literature). The second point is important. The amount of time needed to take up questions can be built into the lesson plan &#8212; I think the best way to approach this is to <em>reduce </em>the amount that we try to cover in the tutorial slide show. Besides, there&#8217;s little advantage to repeating all of the same things as the instructor (particularly if <em>we might say it differently</em>, or <em>explain it in a way that&#8217;s even more confusing</em> or worse, <em>disagree with the instructor</em>). It&#8217;s thus better to focus on giving the background for the workbook questions. I figure that an average of 25% to 33% less material covered will enable us to focus in on the workbook and allow us to discuss quiz questions (and spurious questions) etc. with sufficient time.</p>
<p>Overall, this was a very enjoyable and instructional experience <img src='http://eddiema.ca/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> .</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1910" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/07/18/my-first-ta-evaluations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Null Coalescing Operator (C#, Ruby, JS, Python)</title>
		<link>http://eddiema.ca/2010/07/07/the-null-coalescing-operator-c-ruby-js-python/</link>
		<comments>http://eddiema.ca/2010/07/07/the-null-coalescing-operator-c-ruby-js-python/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 15:00:37 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Pure Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Null Coalescence]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1610</guid>
		<description><![CDATA[Null coalescence allows you to specify what a statement should evaluate to instead of evaluating to null. It is useful because it allows you to specify that an expression should be substituted with some semantic default instead of defaulting on some semantic null (such as null, None or nil). Here is the syntax and behaviour [...]]]></description>
			<content:encoded><![CDATA[<p>Null coalescence allows you to specify what a statement should evaluate to instead of evaluating to null. It is useful because it allows you to specify that an expression should be substituted with some semantic default instead of defaulting on some semantic null (such as null, None or nil). Here is the syntax and behaviour in four languages I use often &#8212; C#, Ruby, JavaScript and Python.</p>
<h3><strong>C#</strong></h3>
<p>Null coalescencing in C# is very straight forward since it will only ever accept first class objects of the same type (or null) as its operator&#8217;s arguments. This restriction is one that exists at compile time; it will refuse to compile if it is asked to compare primitives, or objects of differing types (unless they&#8217;re properly cast).</p>
<p><em>Syntax:</em></p>
<pre>&lt;expression&gt; <strong>??</strong> &lt;expression&gt;</pre>
<p>(The usual rules apply regarding nesting expressions, the use of semi-colons in complete statements etc..)</p>
<p><em>A few examples:</em></p>
<pre>DummyNode a = null;
DummyNode b = new DummyNode();
DummyNode c = new DummyNode();

return a ?? b; // returns b
return b ?? a; // still returns b
DummyNode z = a ?? b; // z gets b
return a ?? new DummyNode(); // returns a new dummy node
return null ?? a ?? null; // this code has no choice but to return null
return a ?? b ?? c; // returns b -- the first item in the chain that wasn't null</pre>
<p>No, you&#8217;d never really have a bunch of return statements in a row like that &#8212; they&#8217;re only there to demonstrate what you should expect.</p>
<h3><strong>Ruby, Python and Javascript<br />
</strong></h3>
<p>These languages are less straight forward (i.e. possess picky nuances) since they are happy to evaluate any objects of any class with their coalescing operators (including emulated primitives). These languages however disagree about what the notion of null should be when it comes to numbers, strings, booleans and empty collections; adding to the importance of testing your code!</p>
<p><em>Syntax for Ruby, Javascript:</em></p>
<pre>&lt;expression&gt; <strong>||</strong> &lt;expression&gt;</pre>
<p><em>Syntax for Ruby, Python:</em></p>
<pre>&lt;expression&gt; <strong>or</strong> &lt;expression&gt;</pre>
<p>(Ruby is operator greedy <img src='http://eddiema.ca/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> .)</p>
<p>The use of null coalescence in these languages are the same as they are in C# in that you may nest coalescing expressions as function arguments, use them in return statements, you may chain them together, put in an object constructor as a right-operand expression etc.; the difference is in what Ruby, Python or Javascript will coalesce given a left-expression operand. The below table summarizes what left-expression operand will cause the statement to coalesce into the right-expression operand (i.e. what the language considers to be &#8216;null&#8217;-ish in this use).</p>
<table border="0">
<tbody>
<tr style="background-color: #e9967a;" align="center" valign="middle">
<td style="text-align: center;"><span style="font-size: small;">Expression as a left-operand</span></td>
<td style="text-align: center;"><span style="font-size: small;">Does this coalesce in Ruby?</span></td>
<td style="text-align: center;"><span style="font-size: small;">Does this coalesce in Python?</span></td>
<td style="text-align: center;"><span style="font-size: small;">Does this coalesce in JavaScript?</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">nil / None / null</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">[]<br />
</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">{}</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">n/a*<br />
</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">0</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">0.0</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">&#8220;&#8221;</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">&#8221;</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">No</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">false / False / false<br />
</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
<td style="text-align: center;"><span style="font-size: small; font-family: andale mono,times;">Yes</span></td>
</tr>
</tbody>
</table>
<p>*Note that in JavaScript, you&#8217;d probably want to use an Object instance as an associative array (hash) so that the field names are the keys and the field values are the associated values &#8212; doing so means that you can never have a null associative array.</p>
<p>Contrast the above table to what C# will coalesce: strictly &#8220;null&#8221; objects only.</p>
<p>The null coalescing operator makes me happy. Hopefully it&#8217;ll make you happy too.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1610" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/07/07/the-null-coalescing-operator-c-ruby-js-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Borrowing Ruby ideas: Returning an object instance</title>
		<link>http://eddiema.ca/2010/06/27/borrowing-ruby-ideas-returning-an-object-instance/</link>
		<comments>http://eddiema.ca/2010/06/27/borrowing-ruby-ideas-returning-an-object-instance/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 07:00:36 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Pure Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Object Oriented Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1623</guid>
		<description><![CDATA[Brief: Ruby conventions were designed to be particularly satisfying and intuitive for the developer. One convention that Ruby adds to the object oriented world is for mutators (setters) to return the object instance &#8212; that is, calling an object&#8217;s mutators will not only alter the object, but will also return the object (not the mutated [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Brief: </strong></em>Ruby conventions were designed to be particularly satisfying and intuitive for the developer. One convention that Ruby adds to the object oriented world is for mutators (setters) to return the object instance &#8212; that is, calling an object&#8217;s mutators will not only alter the object, but will also return the object (not the mutated property). This is especially useful if you want to chain a bunch of mutators together for code legibility or developer convenience.</p>
<p>This would be a welcome shorthand for developers of C-derived object oriented languages such as Java and C#. The following chain&#8230;</p>
<pre>a.setMass(17);
a.setName("cube");
a.setFace(null);
</pre>
<p>&#8230;would become&#8230;</p>
<pre>a.setMass(17).setName("cube").setFace(null);
</pre>
<p>&#8230;a much more compact and what I feel is a more intuitive chain.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1623" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/06/27/borrowing-ruby-ideas-returning-an-object-instance/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Parsing a Newick Tree with recursive descent</title>
		<link>http://eddiema.ca/2010/06/25/parsing-a-newick-tree-with-recursive-descent/</link>
		<comments>http://eddiema.ca/2010/06/25/parsing-a-newick-tree-with-recursive-descent/#comments</comments>
		<pubDate>Sat, 26 Jun 2010 02:00:25 +0000</pubDate>
		<dc:creator>Eddie Ma</dc:creator>
				<category><![CDATA[Computational Biology]]></category>
		<category><![CDATA[Andre Masella]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[Newick Format]]></category>
		<category><![CDATA[parse_newick.js]]></category>
		<category><![CDATA[Phylogeny]]></category>
		<category><![CDATA[Recursive Descent Parser]]></category>

		<guid isPermaLink="false">http://eddiema.ca/?p=1622</guid>
		<description><![CDATA[&#62;&#62;&#62; Attached: ( parse_newick.js &#8211; implementation in JS &#124; index.html &#8211; example use ) &#60;&#60;&#60; Update: Fixed the pseudocode &#8212; the previous version was too wordy, this version is comfortably more algebraic. This method of parsing works for any language that allows recursive functions &#8212; basically any of the curly bracket languages (C#, C, Java) [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family: tahoma,arial,helvetica,sans-serif;">&gt;&gt;&gt; <span style="text-decoration: underline;">Attached</span>: ( <a href="http://eddiema.ca/wp-content/uploads/2010/05/parse_newick.js">parse_newick.js</a> &#8211; implementation in JS | <a href="http://eddiema.ca/wp-content/uploads/2010/05/index.html">index.html</a> &#8211; example use ) &lt;&lt;&lt;<br />
</span></p>
<p><em><strong>Update: </strong>Fixed the pseudocode &#8212; the previous version was too wordy, this version is comfortably more algebraic.</em></p>
<p>This method of parsing works for any language that allows recursive functions &#8212; basically any of the curly bracket languages (C#, C, Java) and the fast-development languages (Ruby, JavaScript, Python) can do this. This particular example will include JavaScript code which you can take and do whatever you want with &#8212; recursive descent parsing is a well-known and solved problem, so it&#8217;s no skin off my back. Before we begin, I should probably explain what a tree in Newick format is.</p>
<p><strong>What exactly <em>is</em> the Newick format?</strong></p>
<p>Remember back in second year CS when your data structures / abstract data types / algorithms instructor said you can represent any tree as a traversal? Well, if not &#8212; don&#8217;t fret, it&#8217;s not hard to get the hang of.</p>
<p>A traversal is a finite, deterministic representation of a tree which can be thought of as a road map of how to visit each node of the tree exactly once. The phylogeny / bioinformatics people will know each of these nodes as either taxa / sequences (the leaves) or profiles (the internal nodes &#8212; i.e. not the leaves). A tree in Newick format is exactly that &#8212; a traversal. More specifically, it is a depth-first post-order traversal. When traversing a tree, we have a few options about how we want to visit the nodes &#8212; depth-first post-order means we want to start at the left-most, deepest leaf, and recursively visit all of the nodes before we end at the root.</p>
<p>A tree expressed in Newick format describes a tree as an observer has seen it having visited each node in a depth-first post-order traversal.</p>
<p>A node in the Newick format can be&#8230;</p>
<ul>
<li>A leaf in the form: &#8220;&lt;<em>name</em>&gt;:&lt;<em>branch_length</em>&gt;&#8221;
<ul>
<li>e.g. &#8220;<span style="font-family: andale mono,times;">lcl|86165:-0</span>&#8220;</li>
<li>e.g. &#8220;<span style="font-family: andale mono,times;">gi|15072471:0.00759886</span>&#8220;</li>
<li>e.g. &#8220;<span style="font-family: andale mono,times;">gi|221105210:0.00759886</span>&#8220;</li>
</ul>
</li>
<li>Or a node in the form &#8220;(&lt;<em>node</em>&gt;,&lt;<em>node</em>&gt;):&lt;<em>branch_length</em>&gt;&#8221;
<ul>
<li>This is where it gets tricky and recursive &#8212; the &#8220;node&#8221; item above can be another node, or a leaf &#8212; when a node is composed of at least another node, we call that a recursive case; when a node is composed of only leaves, we call that a base case. We make this clearer in the next section.</li>
</ul>
</li>
<li>Or a node in the form &#8220;(&lt;<em>node</em>&gt;,&lt;<em>node</em>&gt;);&#8221;
<ul>
<li>The semi-colon at the end means that we have finished describing the tree. There is no branch length as the root of the tree is not connected to a parent.</li>
</ul>
</li>
</ul>
<p><strong>Understanding recursion in a Newick Tree</strong></p>
<p><em>Base case e.g.: The below node is composed of two leaves.<br />
</em></p>
<p>&#8220;<span style="font-family: andale mono,times;">(lcl|86165:-0,gi|87118305:-0):0.321158</span>&#8221;</p>
<p><em>Recursive case e.g.: The below node is composed of a <span style="background-color: #ff99cc;">leaf on the left</span>, and another <span style="background-color: #ccffff;">node on the right</span>; this right-node is composed of two leaves.<br />
</em></p>
<p><span style="font-size: x-small;"><span style="font-family: andale mono,times;">&#8220;(<span style="background-color: #ff99cc;">gi|71388322:0.0345038</span>,<span style="background-color: #ccffff;">(gi|221107809:0.00952396,gi|221101741:0.00952396):0.0249798)</span>:0.0111081</span>&#8220;</span></p>
<p>If the names look a bit funny, that&#8217;s because these are sequences pulled  out of a <em><strong>blastp</strong></em> search.</p>
<p>The Newick tree itself may have any number of nodes, the base case being a single node. The only restriction is that any node either is a leaf (has zero children) or must have two children (never a single child). These two children again are allowed to be either leaves or other nodes.</p>
<p>We would visualize the above <em>Recursive case e.g.</em> as follows.:</p>
<p><img class="aligncenter size-full wp-image-1757" title="blog_newick_subtree_recurs_case_eg" src="http://eddiema.ca/wp-content/uploads/2010/05/blog_newick_subtree_recurs_case_eg.png" alt="" width="341" height="191" /></p>
<p>Where the numbers beside the edges are edge length and the names of the named taxa are indicated inside the circles (leaves). The unnamed internal nodes are the profiles that have been calculated with alignments. You&#8217;ll notice that there&#8217;s a branch length leading out of the root of this <em>subtree</em> into the rest of the tree (not shown). If this was a complete tree on its own, the root would have no branch length there and no arrow coming out of it.</p>
<p><strong>Finally, Parsing!</strong></p>
<p>Now that we have reviewed the depth-first post-order traversal, the Newick format and how to interpret it; we can move onto parsing these things. In parsing, we hope to create an in-memory structure that represents the tree. The parser I discuss assumes that the Newick format string already has had all newlines stripped, as it uses regular expressions. If your trees aren&#8217;t stored that way, just make sure that newlines are stripped before feeding it into my function. The in-memory object that&#8217;s created will have the following fields as a minimum.</p>
<ul>
<li><em>node_type</em> <strong>$left</strong> &#8211; the left child of a node</li>
<li><em>node_type</em> <strong>$right</strong> &#8211; the right child of a node</li>
<li><em>string_type</em> <strong>$name</strong> &#8211; the name of a node (if it is a leaf)</li>
<li><em>float_type</em> <strong>$branch_length</strong> &#8211; the length of the branch coming out of the top of a given node</li>
</ul>
<p>I also use the following two fields to keep track of a few house keeping items and to make life pleasant for future tasks with this in-memory structure.</p>
<ul>
<li><em>node_type</em> <strong>$parent</strong> &#8211; the parent of a node</li>
<li><em>integer_type</em> <strong>$serial</strong> &#8211; the order in which this node occurs when parsed</li>
</ul>
<p>Note that in future, a depth-first post-order traversal will yield the nodes in the exact order that they were read &#8212; so in reality &#8220;this.serial&#8221; isn&#8217;t really needed, but it&#8217;s nice to have for future functions you might write as a shorthand. Have you understood why these nodes would occur in the same order?</p>
<p>Each language has its own quirks. Python and JavaScript have the advantage that you can define a class and define its properties (fields) on the fly &#8212; meaning there&#8217;s less code to download and to write, which is particularly good for blogs <img src='http://eddiema.ca/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Here&#8217;s pseudo-code for the recursive descent parsing function &#8220;tree_builder(&lt;<em>newick_string</em>&gt;)&#8221; &#8212; I don&#8217;t indicate where to strip away newlines because I assume they&#8217;re gone. I also don&#8217;t indicate where to strip away whitespace (I did previously, but that took up like half the pseudocode). So if there&#8217;s a place where you suspect whitespace can occur, strip it away and increment the cursor by the length of that whitespace.</p>
<p><em><strong>Note: </strong>We are assuming that there are no newlines in the file &#8212; that is, the entire newick traversal is one string on a single long unbroken line.</em></p>
<pre class="brush: jscript;">
// Note:
// Call tree_builder() with a &quot;new&quot; operator in JavaScript
//     to allow it to use the 'this' keyword.
// In other languages,
//     you may need to explicitly create a new object instead of using 'this'.

var count = 0; // can be either a global variable or a reference
// keeps track of how many nodes we've seen

var cursor = 0; // also either a global or a reference
// keeps track of where in the string we are

function tree_builder(newick_string) {
    // Look for things relating to the left child of this node //
    if $newick_string [ $cursor ] == '(' {
        $cursor ++; // move cursor to position after '('.
        if newick_string [ $cursor ] == '(' {
            // Then the $left node is an internal node: requires recursion //
            $this.left = new tree_builder(newick_string); // RECURSIVE CALL.
            $this.left.parent = $this;
        }
        // try to find a valid $name next at the current cursor position //
        if $name = $newick_string [ $cursor ] . regex match (&quot;^[0-9A-Za-z_|]+&quot;) {
            // Then the $left node is a leaf node: parse the leaf data //
            $this.left = new Object;
            $this.left.name = $name;
            $this.left.serial = $count;
            $count ++;
            $this.left.parent = $this;
            $cursor += length of $name;
            // move cursor to position after matched name.
        }
        // notice: if no $name found, just skip to finding branch length.
    }
    if $newick_string [ $cursor ] == ':' {
        // Expect left branch length after descending into the left child //
        $cursor ++; // move cursor to position after the colon.
        // look for the string representation of a floating point value &quot;FPV&quot;...
        $branch_length_string =
            $newick_string [ $cursor ] . regex match (&quot;^[0-9.+eE-]+&quot;);
        $this.$left.$score = $branch_length_string as a FPV;
        $cursor += length of the string $branch_length_string;
        // move cursor after FPV.
    }
    // Look for things related to the right node //
    if $newick_string [ $cursor ] == ',' {
        $cursor ++; // move cursor after the comma
        if newick_string [ $cursor ] == '(' {
            // Then the $right node is an internal node: requires recursion //
            $this.right = new tree_builder($newick_string); // RECURSIVE CALL.
            $this.right.parent = $this;
        }
        // try to find a valid $name next at the current cursor position //
        if $name = $newick_string [ $cursor ] . regex match (&quot;^[0-9A-Za-z_|]+&quot;) {
            // Then the $right node is a leaf node: parse the leaf data //
            $this.right = new Object;
            $this.right.name = $name;
            $this.right.serial = $count;
            $serial ++;
            $this.right.parent = $this;
            $cursor += $length of $name;
        }
        // again, accept if no $name found and move onto branch length.
    }
    // Now looking for the branch length ... //
    if $newick_string at $cursor == ':' {
        // Expect right branch length after descending into right child //
        $cursor ++; // moving past the colon.
        $branch_length_string =
            $newick_string [ $cursor ] . regex match (&quot;^[0-9.+eE-]+&quot;);
        $this.right.score = $branch_length_string as a FPV;
        $cursor += length of the string $branch_length_string;
    }
    if $newick_string at $cursor == ')' {
        $cursor ++; // move past ')'.
    }
    // Expect the branch length of $this node after analyzing both children //
    if $newick_string at $cursor == ':') {
        $cursor ++;
        $branch_length_string =
            $newick_string [ $cursor ] . regex match (&quot;^[0-9.+eE-]+&quot;);
        $this.score = $branch_length_string as a FPV;
        $cursor += length of the string $branch_length_string;
    }
    if $newick_string at $cursor == ';') {
        // This case only executes for the root node-- //
        // --the very last node to finish parsing //
        $cursor ++; // to account for the semicolon (optional, consistency)
        $this.serial = $count; // no need to increment $count here
    }
    // Return to complete a recursive instance (internal) or base case (leaf) //
    return this; // not needed if &quot;new&quot; operator was used all along
}
</pre>
<p>The implementation that&#8217;s included in the attached JavaScript does two things differently than the above. First, I don&#8217;t force the user to break encapsulation by declaring globals. Instead, I use an object called &#8220;ref&#8221; which has two fields, &#8220;ref.count&#8221; and &#8220;ref.cursor&#8221;. The name &#8220;ref&#8221; is chosen to remind us that <em>its fields are passed by reference</em>. This is possible because the object &#8220;ref&#8221; itself is passed by reference (I could have called it anything, but I chose a name that suited its purpose). Imagine trying to pass &#8220;count&#8221; and &#8220;cursor&#8221; in this recursive function without an enclosing object &#8212; what would happen instead is that the value wouldn&#8217;t be updated, instead the integer values would be copied and modified locally in the span of single function instances. The &#8220;ref&#8221; object is passed as an argument to the &#8220;_tree_builder(&lt;<em>ref</em>&gt;, &lt;<em>newick_string</em>&gt;)&#8221; function internally where it is instantiated if &#8220;null&#8221; is passed in the place of &#8220;ref&#8221;. The calling user doesn&#8217;t even need to know about it, as it&#8217;s all wrapped together in a pretty package and the user just calls &#8220;tree_builder(&lt;<em>newick_string</em>&gt;)&#8221; as before &#8212; without the need for globals. The enclosing function even does the work of instantiating the root node with the &#8220;new&#8221; keyword so that the end user doesn&#8217;t even need to (and shouldn&#8217;t!) say &#8220;new&#8221;.</p>
<p>Finally, there is a traversal function, and an expose function. The traversal function returns the node objects in an array following in the natural depth-first post-order described previously. The expose function is a debugging function which writes the output using &#8220;thoughts_write(&lt;<em>message</em>&gt;)&#8221; which wraps &#8220;document.write(&lt;<em>message</em>&gt;)&#8221;. You can change &#8220;thoughts_write(&lt;<em>message</em>&gt;)&#8221; to print output elsewhere using &#8220;document.getElementById(&lt;<em>some_identity</em>&gt;).innerHTML += (&lt;<em>message</em>&gt;)&#8221; where &#8220;some_identity&#8221; is the &#8220;id&#8221; of some element in your HTML. Without going into detail, the traversal function also uses an internal &#8220;ref&#8221; object which refers to the array as it is filled.</p>
<p><strong>Some other things you can try&#8230;</strong></p>
<p>The JavaScript recursive descent parser is actually a simplified version of something that I threw together earlier. The major difference is that I tag leaf nodes with <em><strong>fasta</strong></em> protein sequences by passing a reference to an associative array (or hash) as an argument to &#8220;tree_builder(&lt;<em>newick_string</em>&gt;, &lt;<em>fasta_hash</em>&gt;)&#8221;. Remember, in JavaScript, an associative array is an instance of an Object, not an instance of an Array. <em>Using non-integer field names in an Array is actually not well defined</em> but kind of sort of works semi-consistently between browsers (i.e. don&#8217;t try!), but that&#8217;s a story for another day. Whenever the name of a leaf is parsed, I would look it up in the hash and put it in a field either &#8220;this.left.fasta&#8221; or &#8220;this.right.fasta&#8221; thereby conferring to the leaf nodes of the in-memory structure the appropriate fasta protein sequence.</p>
<p><strong>Lessons Learned</strong></p>
<p>In putting this thing together, I managed to relearn JS, recursive descent parsing and making JS pass things by reference up and down a recursive stack of function calls. <a href="http://www.masella.name/">Andre Masella</a> helpfully reminded me that I didn&#8217;t need to use any kind of BNF or LALR(1) parser &#8212; just an easy single-function parser would do. This is actually a port of a C# parser which does the same thing that I wrote in an earlier step for phylogenetic analysis &#8212; the difference being that C# offers a &#8220;ref&#8221; keyword that allows one to specify arguments in a function&#8217;s parameter list as emulated references (functionally equivalent to using C&#8217;s asterisk and ampersand convention though not operationally equivalent).</p>
<p>Happy parsing! The code presented should be easy enough to understand for you to port it into the language of your choice for whatever purposes you design.</p>
 <img src="http://eddiema.ca/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1622" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://eddiema.ca/2010/06/25/parsing-a-newick-tree-with-recursive-descent/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
